简体   繁体   English

在尝试将字符串传递给函数时获取错误分段错误(核心转储)

[英]getting error Segmentation fault (core dumped) when trying to pass a string to a function

When I try to pass the current time as a string to the function logger in my code I get an error saying that "Segmentation fault (core dumped)". 当我尝试将当前时间作为字符串传递给我的代码中的函数记录器时,我得到一个错误,说“分段错误(核心转储)”。 but when I put static char str[30] the error doesn't come. 但是当我把static char str[30]放入错误时。 but with no errors the resulting file makes impossible to open it. 但没有错误,生成的文件无法打开它。

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;

}

so previously I made the currentTime function like this 所以我以前做过currentTime函数

char * currentTime(void) {
    time_t rawtime;
    struct tm * timeinfo;
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    return asctime(timeinfo);
}

it works fine but that is not the way I need to display the time. 它工作正常,但这不是我需要显示时间的方式。

You are returning a local variable from function currentTime() which is undefined behaviour . 您正在从函数currentTime()返回一个局部变量,该变量是未定义的行为

Change function signature to: char * currentTime(char *inputBuffer, size_t bufLen) 将函数签名更改为: char * currentTime(char *inputBuffer, size_t bufLen)

You are returning a pointer to a local variable (here the str buffer) from the currentTime function. 您正在从currentTime函数返回指向局部变量(此处为str缓冲区)的指针。

You cannot do this, because as soon as local variables goes out of scope (that is when you leave the currentTime function), their content is undefined, they will most of the time contain garbage. 你不能这样做,因为一旦局部变量超出范围(即你离开currentTime函数),它们的内容是未定义的,它们大多数时候都会包含垃圾。

Therefore you must declare str as static: 因此,您必须将str声明为static:

static char str[30];

In that case str exists all the time during the execution of your program and not only during the execution of the currentTime function. 在这种情况下, str在程序执行期间始终存在,而不仅仅是在执行currentTime函数期间。

But this can cause other problems. 但这可能会导致其他问题。

Example: 例:

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        */

Or problems when you use threads. 或者使用线程时的问题。

For the reasons exposed in other answers your function is not reentrant meaning that each time you call it the result is overwritten. 由于在其他答案中暴露的原因,您的功能不是可重入的,这意味着每次调用它时结果都会被覆盖。 To create a dedicated instance for each call you can also simply use an strdup() to create a duplicate of your string that can be deleted using free() after use: 要为每个调用创建一个专用实例,您还可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM