【发布时间】:2017-09-27 03:26:10
【问题描述】:
我的 c 代码在下面,它工作正常一次,再次调用该函数后,它给出了相同的结果。缓冲区未更新。
#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
char *EpochToMMDDYYYY(long );
int main() {
long epoch = 1492151737;
printf("date of %ld is %s\n",epoch,EpochToMMDDYYYY(epoch));
long ep = 1492222737;
printf("date of %ld is %s\n",epoch,EpochToMMDDYYYY(ep));
long epc = 1491111737;
printf("date of %ld is %s\n",epoch,EpochToMMDDYYYY(epc));
return 0;
}
char *EpochToMMDDYYYY(long ep)
{
struct tm tm;
char b[25];
memset(b,0,sizeof(b));
//setenv("TZ", "PST8PDT", 1);
/* set your own time zone PST8PDT for PDT timezone */
//tzset();
char epoch[20];
sprintf(epoch,"%ld",ep);
memset(&tm, 0, sizeof(struct tm));
strptime(epoch, "%s", &tm);
strftime(b, sizeof(b), "%m%d%Y", &tm);
puts(b); /* -> 04 24 2017 */
return b;
}
输出如下
04142017
date of 1492151737 is 04142017
04142017
date of 1492151737 is 04142017
04022017
date of 1492151737 is 04022017
谁能告诉我这背后的原因,以及解决方法?
【问题讨论】:
-
b在EpochToMMDDYYYY函数范围之外无效。 -
我在哪里可以进行替换以获得准确的输出? @BLUEPIXY
-
char b[25];-->static char b[25];简单修复 -
返回指向函数返回后不再存在的指针。使用它会导致调用者表现出未定义的行为。
-
1 谢谢@BLUEPIXY
标签: c pointers memory memory-leaks