Check meaningful return values
suggest changeMany standard-library functions report failure through their return value. Check the result whenever later operations depend on the call succeeding. Ignoring an allocation or input failure can turn a recoverable error into undefined behavior.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *text = malloc(128);
if (text == NULL) {
perror("malloc");
return EXIT_FAILURE;
}
if (fgets(text, 128, stdin) == NULL) {
if (ferror(stdin)) {
perror("stdin");
} else {
fputs("End of input\n", stderr);
}
free(text);
return EXIT_FAILURE;
}
printf("Read: %s", text);
free(text);
return EXIT_SUCCESS;
}
Not every return value must be used. It is reasonable to ignore a result when the function's contract makes that intentional and no recovery is possible or required. Make that decision explicitly rather than assuming the call succeeded.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents