Reputation: 6725
I want to allocate some memory on the heap that is not reachable from any stack pointer. (This is for test purpose).
void *ptr = malloc(sizeof(int));
void *ptr2 = malloc(sizeof(int));
ptr = ptr2;
If I do this code, I think that ptr and ptr2 at the start is two pointers on the stack referring to some allocated memory on the heap, right? And then when I do the ptr = ptr2, the first mallocated memory is still on the heap but not reachable in any way from the stack. Is that so?
I have a program that is searching the stack to find all alive objects on the heap, therefore I want to test that it actually works.
Upvotes: 0
Views: 134
Reputation:
It's even simpler to do than that, here is an example from wikipedia:
#include <stdlib.h>
void function_which_allocates(void) {
/* allocate an array of 45 floats */
float * a = malloc(sizeof(float) * 45);
/* additional code making use of 'a' */
/* return to main, having forgotten to free the memory we malloc'd */
}
int main(void) {
function_which_allocates();
/* the pointer 'a' no longer exists, and therefore cannot be freed,
but the memory is still allocated. a leak has occurred. */
}
As soon as the pointer to 'a' goes out of scope, the memory is leaked, as 'a' was never freed.
Upvotes: 0
Reputation: 70951
A more subtile leak to find would be introduced by doing
malloc(0);
though.
Upvotes: 0
Reputation: 3761
if you simply put your code into a function, then you have a memory leak as soon as your function ends and ptr and ptr2 get out of scope.
Upvotes: 0
Reputation: 281187
That works. It's more complex than necessary, though:
malloc(4);
The easiest way to leak memory is to just not save a reference to it in the first place.
Upvotes: 5