The static
keyword keeps the pointer alive until the program terminates, but is the memory allocated to the pointer buffer
free'd automatically when the process terminates? or does the programmer have to do it?
In the following example, we do not know how many times the function will be called and we can only free the allocated memory if we haven't read anything on the current call of the function. Otherwise the memory cannot be free'd since we will need to use the bytes that we just read in the next call.
Function:
char *readStdin(void) {
static char *buffer = NULL;
ssize_t ret;
if (buffer != NULL) {
// DO SOMETHING WITH PREVIOUSLY READ BYTES
}
/* Allocate and NULL-terminate a Buffer */
buffer = malloc(BUFSIZ);
if (buffer == NULL)
return (NULL);
buffer[BUFSIZ] = '\0';
/* Read from Standard Input at most 'BUFSIZ' characters*/
ret = read(0, buffer, BUFSIZ);
/* Free Buffer if no Input Read */
if (ret <= 0) {
free(buffer);
buffer = NULL;
}
/* Return the read Input */
return (buffer);
}
Program:
int main(void) {
/* Print the Read Bytes */
printf("%s", readStdin());
printf("%s", readStdin());
printf("%s", readStdin());
...
}