I'm new to C++ and would like to ask if the code below is an example of a dangling pointer or a memory leak because it is pointing outside the dynamically allocated array:
int * n = new int[10];
for (int prev = 0; prev < 10; prev++) {
*n = *(n + prev + 1);
}
delete[] n;
n = nullptr;
On a Linux system, a memory fault is called a segmentation fault. When a memory fault occurs, the OS terminates the process immediately . A dangling pointer is a pointer to memory that your program should not use.
In another word, you can say that a memory leak is a type of resource leak. Note: once you allocate memory than allocated memory does not allocate to another program or process until it gets free. Let’s see the dangling pointer and memory leak in-depth to understand the difference between a dangling pointer and a memory leak in C.
Generally, daggling pointers arise when the referencing object is deleted or deallocated, without changing the value of the pointers. In opposite of the dangling pointer, a memory leak occurs when you forget to deallocate the allocated memory.
Dangling Pointer. If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.
A dangling pointer is a pointer which points to an address where no object resides. I.e. it points at invalid memory. The word "dangling" usually carries the connotation that it used to point to something valid and that something got destroyed (either because it was explicitly deallocated or because it went out of scope).
A memory leak happens when you lose all track of dynamically allocated piece of memory; that is, when you "forget" last pointer that was pointing to that memory, meaning you can no longer deallocate it. Your code would create a memory leak if you did n = nullptr;
before you call delete[] n;
.
If I had to describe your case with one of these two terms, it would be "dangling pointer," simply because you're reaching beyond the buffer in the last iteration. However, I wouldn't normally call it a "dangling pointer," because it was never valid in the first place. I would call this a "buffer overrun" or an "out-of-bounds access."
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