C Returning char[] Warning “returns address of local variable” [duplicate]

纵饮孤独 提交于 2019-11-30 10:06:15

char line[30]; is an array with automatic storage duration. Memory where it resides is deallocated once the execution goes out of the scope of your function, thus pointer to this memory that you return becomes invalid (dangling pointer).

Trying to access memory, that has already been deallocated, results in undefined behaviour.

You can allocate your array dynamically and let the caller explicitly deallocate it:

char *getLine() {
    char* line = malloc(30);
    ...
    return line;
}

// somewhere:
char* line = getLine();
...
free(line);

Alternative without using malloc, not covered by the earlier questions as far as I could find:

/* Warning, this function is not re-entrant. It overwrites result of previous call */
char *getLine(FILE *input) {
    static char line[30];
    return fgets(line, sizeof(line), input);
    /* fgets returns NULL on failure, line on success, no need to test it */
}

Explanation: static variables in function scope retain their values even after function returns. There's just one instance of such a variable, same one is used in every call to that function (so not re-entrant/thread-safe). Memory for static variables is allocated when program starts, it's neither heap nor stack but it's own reserved area in running program's memory space. Value of static variable is initialized just once, before it's first used (above does not have specific initialization, so it's filled with 0, but it could have an initializer too, and that would only be it's value when function is called first time).

While using static variable in this manner may seem a bit hacky (and I agree it is), it's still a valid pattern also employed by standard C for example with strtok() function. It also demonstrates the need for a version which is re-entrant, as C standard also has strtok_r(), which is more complex to use as it has one extra parameter instead of having local static variable in it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!