A memory leak occurs when dynamically allocated heap memory remains unreleased after the pointer that addresses it goes out of scope. In C, returning from a function releases the pointer variable but not memory obtained with malloc(); free(a) must release it explicitly. section 4.1.1
Early return leaves an allocation behind
leaky_func allocates an integer, then returns when fopen fails. Because the error path skips free(a), the allocation leaks. The successful path closes the file and frees the memory. section 4.1.1
void leaky_func() {
FILE *fp;
int *a = malloc(sizeof(int));
*a = 0; #1
// try to open a file for reading
fp = fopen("file.txt", "r");
if (fp == NULL) {
// there was an error!
return;
}
// Now we can read from the file at fp.
// ...
fclose(fp); #2
free(a); #3
}
Trace the allocation, failed file-opening branch, cleanup calls, and the missing free(a) on the early-return path. section 4.1.1
C++ addresses this hazard through constructors and destructors, with shared_ptr and ifstream shown as objects that support cleanup when control leaves the function. section 4.1.1




