I don't understand the difference between a dangling pointer and a memory leak. How are these two terms related?
Dangling pointers arise during object destruction, when an object that has an incoming reference is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.
DEFINITION A memory leak is the gradual deterioration of system performance that occurs over time as the result of the fragmentation of a computer's RAM due to poorly designed or programmed applications that fail to free up memory segments when they are no longer needed.
Dangling pointer occurs at the time of the object destruction when the object is deleted or de-allocated from memory without modifying the value of the pointer. In this case, the pointer is pointing to the memory, which is de-allocated.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With