Let's say we've got some code like this:
int main() {
FILE *f_conf = fopen("conf.conf");
/* File Open Error Handling */
char *buf = malloc(128);
/* Malloc Error Handling */
fgets(buf, 128, f_conf);
fclose(f_conf);
pid_t pid = fork()
/* Fork Error Handling */
if (pid) {
free(buf); /* Should this free be called? */
return 0;
}
while (1) {
/* Do Stuff */
}
return 0;
}
In general, I prefer to free memory prior to returning, since any impact to impact performance is minimal, and it helps with automated tooling to detect memory leaks. That said, the performance / best practices are less clear to me here, as it makes little sense to run these tools on a daemon. This leads me to two questions:
- Would freeing memory (such as
*buf
) of a parent process prior to return affect performance of the child? I'm thinking there could be some (either positive or negative) by the way copy-on-write is implemented. - Is it considered good practice for the parent to
free
leftover resources?
free
ing the memory would probably cause it to get copied (depending on how the allocator is implemented, but most of the ones I know store metadata right before the allocated memory which will get updated byfree
), which ironically will use up extra physical memory.