jiayi之前写过《被localtime()耍了一下下》(此文已删),把free()失败的原因归于localtime()返回的是一指向static类型的指针。但经我们论坛ericyosho大牛的站内指正,其实问题在于内存泄露…time_struct经malloc后被分到堆上,然后又指向堆栈,所以内存已经被泄露了。。。
但后来又一想,为什么把localtime()换成localtime_r()后就没问题呢?我的理解是,localtime_r(&time_val,time_struct)直接向time_struct指向的内存写数据,而并没有改变它指向的地址。
哎,书上本来没有用malloc(),我心血来潮,硬给加上,引出这么多套头。不过能把问题搞明白,也算是因祸得福,恩~
再次感谢ericyosho
下面是错误代码
CODE
-
#define _XOPEN_SOURCE
-
#include<time.h>
-
#include<stdio.h>
-
#include<stdlib.h>
-
#include<string.h>
-
-
int main()
-
{
-
char buf[256];
-
char *s;
-
time_t time_val;
-
struct tm *time_struct;
-
time_struct=(struct tm *)malloc(sizeof(*time_struct));
-
-
(void)time(&time_val);
-
time_struct=localtime(&time_val);
-
(void)strftime(buf,256,"%A %d %B,%I:%M %p",time_struct);
-
-
(void)strncat(buf," haha",7);
-
s=strptime(buf,"%A %d %B,%I:%M %p",time_struct);
-
printf("local time is %d-%02d-%02d %02d:%02d:%02d
",time_struct->tm_year+1900,time_struct->tm_mon+1,time_struct->tm_mday,time_struct->tm_hour,time_struct->tm_min,time_struct->tm_sec); -
-
free(time_struct);
-
return 0;
-
}
编译执行,提示对内存进行了错误的操作,free()出了问题…
有两种改发:
1.16句换成localtime_r(&time_val,time_struct)
2.去掉13和26句
如果您喜欢本文,欢迎订阅我的文章:
http://feed.jiayii.com
转载请注明出处:http://www.jiayii.com/be-tricked-by-localtime-two-times/
谢谢您的关注。 : @jiayisuse : jiayisuse#gmail.com
转载请注明出处:http://www.jiayii.com/be-tricked-by-localtime-two-times/
谢谢您的关注。 : @jiayisuse : jiayisuse#gmail.com


技术不过关就只有被电脑忽悠的份罗,哈哈!
[Reply]
=。= zt了。。。
PHP回头再看C需要一个过程…PHP把人弄傻了
[Reply]