+ 6

What does it mean: “A memory leak is occurring.”?

What is the problem with the following code? int *p = (int*) malloc(sizeof(int)); p = NULL; free(p);

27th Apr 2020, 12:54 PM
Solo
Solo - avatar
6 Respostas
+ 4
Memory leaks generally occur when an allocated memory is never deallocated. In this case the pointer is allocated a memory of 4 bytes but in the very next line you assign it to NULL. So the allocated memory is never returned because in the free(p), p is not pointing to the memory allocated anymore. So there is leak or wastage of memory.
27th Apr 2020, 1:08 PM
Avinesh
Avinesh - avatar
+ 4
Avinesh ok thanks for the clarification 🙋
27th Apr 2020, 1:36 PM
Solo
Solo - avatar
+ 3
Avinesh, yes - memory loss sounds much better than a leak. A leak in my opinion implies a partial loss, that is, there were 4 bytes, and there became 2 bytes
27th Apr 2020, 1:27 PM
Solo
Solo - avatar
+ 3
coffeeunderrun thanks for the help, this is an example from the challenge.
27th Apr 2020, 1:31 PM
Solo
Solo - avatar
+ 1
Vasiliy it is because of the same reason it is called a memory leak. A memory which you don't have access to anymore, something that is never to return.
27th Apr 2020, 1:32 PM
Avinesh
Avinesh - avatar