+ 2

[Solved] Question from challenges

What is the problem with following code? int *p = (int*)malloc(sizeof(int)) ; p = NULL; free(p) ; -Compiler error: free can't be applied on NULL pointer. ✔️There is a memory leak. (correct answer) -p becomes a dangling pointer. -The program will crash as a NULL pointer is passed to free() The question is why would this cause memory leak?

27th Oct 2019, 11:47 AM
voja
voja - avatar
2 Réponses
+ 4
The program allocates memory but can never free it because p is set to NULL and therefore the address of the allocated memory is lost. This is called a memory leak because if this e.g. would be done in a loop or with larger memory blocks a program would claim more and more memory without freeing it until eventually no more memory is available anymore.
27th Oct 2019, 12:31 PM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 2
Nicely explained, yes, makes total sense now. Thanks Aaron Eberhardt 👌
27th Oct 2019, 1:11 PM
voja
voja - avatar