当我测试gmtime函数时,会发生错误。
#include<stdio.h>
#include<sys/time.h>
#include<time.h>
#include<stdlib.h>
int main(void) {
struct timeval *tv = (struct timeval *)malloc(sizeof(struct timeval));
struct timezone *tz = NULL;
struct tm *aTm = (struct tm *)malloc(sizeof(struct tm));
int r = 0;
r = gettimeofday(tv, tz);
if (r == -1) {
printf("gettimeofday error");
return 1;
}
aTm = gmtime(&tv->tv_sec);
printf("%s", ctime(&tv->tv_sec));
printf("%d\n", (int)time(&tv->tv_sec));
printf("%d-%d-%d %d:%d:%d\n", (Tm->tm_year+1900), (Tm->tm_mon+1), Tm->tm_mday, Tm->tm_hour, Tm->tm_min, Tm->tm_sec);
free(tv);
printf("%p\n", aTm);
free(aTm); //there is an error
return 0;
}
我的机器:
Linux jim 3.13.0-62-generic #102-Ubuntu SMP Tue Aug 11 14:29:36 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
gcc版本:
gcc-4.8.real (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
错误:
*** Error in `./a': free(): invalid pointer: 0x00007f1dfe9b4de0 ***
segmentation fault
gdb消息:
(gdb) run
Starting program: /tmp/a
0x7ffff7dd8de0
*** Error in `/tmp/a': free(): invalid pointer: 0x00007ffff7dd8de0 ***
Program received signal SIGABRT, Aborted.
0x00007ffff7a4bcc9 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
56 ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory
我没有将aTm参数更改为静态值,当我释放它时,会发生错误。
谁能帮助我。答案 0 :(得分:3)
aTm = gmtime(&tv->tv_sec);
...
free(aTm); //there is an erro
您只能传递free
来自malloc
的内容,而不是gmtime
返回的指针!
你可能想要:
memcpy (aTm, gmtime (&tv->tv_sec), sizeof (struct tm));
或者只是:
*aTm = * gmtime(&tv->tv_sec);
这会将gmtime
的返回值复制到现有缓冲区中,而不是将指针更改为指向库的缓冲区。