0 votes
in C Plus Plus by
What are dangling pointers? How are dangling pointers different from memory leaks?

1 Answer

0 votes
by

The dangling pointer points to a memory that has already been freed. The storage is no longer allocated. Trying to access it might cause a Segmentation fault. A common way to end up with a dangling pointer:

#include<stdio.h>
#include<string.h>

char *func()
{
    char str[10];
    strcpy(str,"Hello!");
    return(str);
}

You are returning an address that was a local variable, which would have gone out of scope by the time control was returned to the calling function. (Undefined behavior)

*c = malloc(5izeof(int));
free(c);
*c = 3; //writing to freed location!

In the figure shown above writing to a memory that has been freed is an example of the dangling pointer, which makes the program crash.

A memory leak is something where the memory allocated is not freed which causes the program to use an undefined amount of memory from the ram making it unavailable for every other running program(or daemon) which causes the programs to crash. There are various tools like O profile testing which is useful to detect memory leaks on your programs.

void function(){
	char *leak = malloc (10);	//leak assigned but not freed
}
...