+ 1
Will saving a memory location in a pointer and deleting that pointer clear the memory address of the value that it holds?
Here is a simple program to implement stacks using singly-;linked-lists in C++. https://code.sololearn.com/cbU4UigrWSNR/#cpp Consider the function Pop(). I implemented it in the following way : void Pop(Node* val) { if(val!=NULL) val = val->next; } However, my teacher told me that though I move the list pointer to the previous element, the element deleted still exists in memory, and thus, I must delete it using the following way : void Pop(Node* val) { if(val!=NULL) {Node* ptr = start; val = val->next; delete ptr;} } Now, how does copying a value in a pointer and deleting the 'new' pointer delete the original data as well? Or this doesn't delete the value, but the reference instead?
4 ответов
+ 5
Yes because you copy the address value so the memory will be freed in the same place. But you will have a "dangling pointer" for the original pointer because the memory will have been freed.
+ 1
Yes you should do this.
When you use delete on a pointer, it unallocates the memory that the pointer points to. When you copy (assign) a pointer, this copies the address of the pointer to the new pointer. You can then access the value using either pointer. You can also use delete on either pointer. If you do this neither pointer can access the value that was there as they point to the same address.
If you don't use delete on allocated memory (from a new statement) then when you move the pointer you will not access to it, but memory will still be allocated and therefore not available. This means that if your stack has enough push and pops it could run out memory, even though it's using much at anyone time.
This called a memory leak and it's not good!
This is one of the reasons computers crashed so in the 90's.
+ 1
@Jared Bird
Thank You!
+ 1
@Karl T.
Thank You!