As a few people have pointed out, modern OS's reclaim memory on exit. However, it is considered a best practice to free your resources anyway, as this makes debugging easier. For example, if you are trying to find a leak and you use a tool like valgrind, all the memory you don't properly free (even if by the program logic, this doesn't matter) will appear as leaks. There are some large API's around that notoriously don't do this, and they make tracking leaks in applications which use them a nightmare.
Also, in some specialized environments it might be important to clean up after yourself. Therefore, it's a good habit to get into now.
A clean-up technique you'll see occasionally (eg, in the linux kernel) is something I think of as the "bail and release" pattern. It's one of the few (perhaps: only) contexts where goto
is still considered acceptable. It depends upon you being able to free your resources in the opposite order you allocated them. Usually this is in the context of a single function, in this case main()
:
#include <stdlib.h>
int main(void) {
int exit_status = EXIT_FAILURE;
char *s1, *s2, *s3;
s1 = malloc(100);
if (!s1) return EXIT_FAILURE;
s2 = malloc(100);
if (!s2) goto endB;
s3 = malloc(100);
if (!s3) goto endA;
exit_status = EXIT_SUCCESS;
/* do whatever */
free(s3);
endA:
free(s2);
endB:
free(s1);
return exit_status;
}
To explain: if allocating s1
fails, we just return -- there is nothing to clean-up. But if allocating s2
fails, we goto endB
, freeing s1
. If allocating s3
fails, we goto endA
, which will free s2
and s1
. Finally, if everything succeeded, we do whatever, and afterward, all three pointers will be freed. If this were a normal function, we might be returning a pointer, so there would be a separate return for that before the "end" bits, which would complete with "return null" instead.
Nb: please don't take this as a licence to make free-wheeling use of goto
!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…