c - possible memory leak by returning "local" heap-allocated object -


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, right in assuming memory in empty_ptr still exists? impossible free , therefore bad code?

the "int *empty_ptr" (the pointer allocated memory block) never released, return value do_memory.

if want no leaks, use this

int* do_memory() {   int * empty_ptr = (int *) malloc(sizeof(int));   *empty_ptr = 5;    return empty_ptr; } ... int* b = do_memory(); int b_local = *b; free(b); // valid 

or (no leaks, no allocations except var on stack, no performance hit):

void do_memory(int* retvalue) {   *retvalue = 5; } ... /// b allocated locally on stack int b; do_memory(&b); // no free() calls needed 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -