Alex Rivera | Logout

Difference between dangling pointer and memory leak

Asked 2012-10-30T04:48:28.093
86

I don't understand the difference between a dangling pointer and a memory leak. How are these two terms related?

c
Edit
Report

1 Answer

23

You can think of these as the opposites of one another.

When you free an area of memory, but still keep a pointer to it, that pointer is dangling:

char *c = malloc(16);
free(c);
c[1] = 'a'; //invalid access through dangling pointer!

When you lose the pointer, but keep the memory allocated, you have a memory leak:

void myfunc()
{
    char *c = malloc(16);
} //after myfunc returns, the the memory pointed to by c is not freed: leak!
answered 2012-10-30T04:54:40.607

Your Answer