Q:

Difference between dangling pointer and memory leak

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

A:

A dangling pointer points to memory that has already been freed. The storage is no longer allocated. Trying to access it might cause a Segmentation fault.
Common way to end up with a dangling pointer:
char *func()
{
   char str[10];
   strcpy(str, "Hello!");
   return str; 
}
//returned pointer points to str which has gone out of scope. 

You are returning an address which was a local variable, which would have gone out of scope by the time control was returned to the calling function. (Undefined behaviour)
Another common dangling pointer example is an access of a memory location via pointer, after free has been explicitly called on that memory.
int *c = malloc(sizeof(int));
free(c);
*c = 3; //writing to freed location!

A memory leak is memory which hasn't been freed, there is no way to access (or free it) now, as there are no ways to get to it anymore. (E.g. a pointer which was the only reference to a memory location dynamically allocated (and not freed) which points somewhere else now.)
void func(){
    char *ch = malloc(10);
}
//ch not valid outside, no way to access malloc-ed memory

Char-ptr ch is a local variable that goes out of scope at the end of the function, leaking the dynamically allocated 10 bytes.

A:

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!

A:

A dangling pointer is one that has a value (not NULL) which refers to some memory which is not valid for the type of object you expect.  For example if you set a pointer to an object then overwrote that memory with something else unrelated or freed the memory if it was dynamically allocated.
A memory leak is when you dynamically allocate memory from the heap but never free it, possibly because you lost all references to it.
They are related in that they are both situations relating to mismanaged pointers, especially regarding dynamically allocated memory.  In one situation (dangling pointer) you have likely freed the memory but tried to reference it afterwards; in the other (memory leak), you have forgotten to free the memory entirely!

