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.