int do_memory()
{
int * empty_ptr = (int *) malloc(sizeof(int));
*empty_ptr = 5;
return *empty_ptr;
}
...
int b = do_memory();
free(&b); //obviously not valid
When b goes out of scope, I would be right in assuming the memory in empty_ptr still exists? But is impossible to free and therefore this is bad code?
The “int *empty_ptr” (the pointer to the allocated memory block) is never released, you just get the return value from do_memory.
If you want no leaks, use this
or this (no leaks, no allocations except the var on stack, no performance hit):