+ 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?
2 Respuestas
+ 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.
+ 2
Nicely explained, yes, makes total sense now. Thanks Aaron Eberhardt 👌