> Is it a good practice to free memory before exiting the program?
Yes in general.
> I've read many places online that since modern operating systems reclaim all resources before exiting, there's no need to free memory.
"All" is an over simplification.
If you're talking about modern desktop OS, then memory from using malloc is reclaimed.
Put it this way, if I ran valgrind with your program and found no memory leaks, I would be a lot more confident that you'd been paying attention to all the details.
You can avoid a lot of the tediousness through careful arrangement of the code.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAME_LENGTH 30
void dowork(char *name, size_t buflen) {
fputs("Enter your name: ", stderr);
fflush(stderr);
if (fgets(name, buflen, stdin) == NULL) {
fputs("Either EOF was encountered and no bytes were read, or an error"
" ocurred when reading from standard input\n", stderr);
} else {
char *newline = strchr(name, '\n');
if (newline != NULL) {
*newline = '\0';
}
printf("Hello %s\n", name);
}
}
int main(void) {
char *name = malloc(NAME_LENGTH);
if (name == NULL) {
fputs("Not enough memory\n", stderr);
exit(EXIT_FAILURE);
} else {
dowork(name, NAME_LENGTH);
free(name);
}
return 0;
}