![](/img/trans.png)
[英]Why am I getting Segmentation fault (core dumped) or bus error (core dumped) when trying to populate a struct?
[英]getting error Segmentation fault (core dumped) when trying to pass a string to a function
当我尝试将当前时间作为字符串传递给我的代码中的函数记录器时,我得到一个错误,说“分段错误(核心转储)”。 但是当我把static char str[30]
放入错误时。 但没有错误,生成的文件无法打开它。
void logger(char * logType, int loggingLevel, char * massage)
{
FILE *fp = fopen("log.txt", "a");
fprintf(fp, "%s|%d|%s|%s",logType,loggingLevel,massage,currentTime());
fclose(fp);
}
char * currentTime(void)
{
time_t rawtime;
char str[30];
char *string;
struct tm * timeInfo;
time(&rawtime);
timeInfo = localtime(&rawtime);
strftime(str, 26, "%Y:%m:%d %H:%M:%S", timeInfo);
return str;
}
所以我以前做过currentTime函数
char * currentTime(void) {
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
return asctime(timeinfo);
}
它工作正常,但这不是我需要显示时间的方式。
您正在从函数currentTime()
返回一个局部变量,该变量是未定义的行为 。
将函数签名更改为: char * currentTime(char *inputBuffer, size_t bufLen)
您正在从currentTime
函数返回指向局部变量(此处为str
缓冲区)的指针。
你不能这样做,因为一旦局部变量超出范围(即你离开currentTime
函数),它们的内容是未定义的,它们大多数时候都会包含垃圾。
因此,您必须将str
声明为static:
static char str[30];
在这种情况下, str
在程序执行期间始终存在,而不仅仅是在执行currentTime
函数期间。
但这可能会导致其他问题。
例:
char *time1;
char *time2;
time1 = currentTime();
...
/* somewhat later */
time2 = currentTime();
/* now time1 and time2 point to the same memory location */
/* which contains the current time at the second call */
或者使用线程时的问题。
由于在其他答案中暴露的原因,您的功能不是可重入的,这意味着每次调用它时结果都会被覆盖。 要为每个调用创建一个专用实例,您还可以使用strdup()
创建一个字符串的副本,可以在使用后使用free()
删除:
void logger(char * logType, int loggingLevel, char * massage)
{
FILE *fp = fopen("log.txt", "a");
char *sTime = currentTime(); //Get the value
fprintf(fp, "%s|%d|%s|%s",logType,loggingLevel,massage, sTime);
free(sTime); //Release the string if no more needed.
fclose(fp);
}
char * currentTime(void)
{
time_t rawtime;
char str[30];
struct tm * timeInfo;
time(&rawtime);
timeInfo = localtime(&rawtime);
strftime(str, 26, "%Y:%m:%d %H:%M:%S", timeInfo);
return strdup(str);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.