This question already has answers here:
Deleting C++ pointers to an object
(9 answers)
Why pointer is not NULL after using delete in C++
(2 answers)
Closed 4 years ago.
I've created a dynamic object in C++ using pointer. I set the value for the dynamic object. Then I delete pointer, but when I try to print the value of dynamic object, it is stay the same.
I have tried to print the value of pointer which is the address of the dynamic object, it is stay the same before and after I delete pointer.
#include<iostream>
using namespace std;
struct students
{
string name;
int agee;
};
int main()
{
students *p = NULL;
p = new students;
(*p).name = "Vu Trung Nghia";
(*p).agee = 20;
cout << p->name << " " << p->agee << endl;
delete p;
if(p == NULL)
cout << "It was deleted";
else
cout << (*p).name << " " << (*p).agee << endl;
}
I expect the result is: p == NULL or can't print "Vu Trung Nghia 20"
Actual result: "Vu Trung Nghia 20"
I expect the result is: p == NULL
There is no reason to expect that, since you never assigned p = NULL.
I have tried to print the value of pointer which is the address of the dynamic object, it is stay the same before and after I delete pointer.
This is the expected behaviour. Deleting a pointer has no effect on the value of the pointer.
but when I try to print the value of dynamic object, it is stay the same.
Behaviour of accessing a destroyed object is undefined. You don't ever want your program to have undefined behaviour.
When the behaviour is undefined, anything could happen. "I try to print the value of dynamic object, it is stay the same." is one of the possible behaviours.
So what deleting a pointer really is?
Assuming the pointer points to an object that was allocated with new, then delete destroys the pointed object, and deallocates the memory. Deallocation means that a subsequent new may re-use that memory.
delete frees the pointer from memory, it does NOT change its value or address, the value stays there, the calls which you do after deleteing it invokes Segmentation fault (which can easily be translated to your program having Undefined behvaior)...
This is the reason why people set the pointer to NULL after invoking delete...
delete p;
p = nullptr; // Stop memory leaking...
You will also find that you are no more able to modify the pointer:-
(*p).name = "Hello!"; /* Value is freed/destroyed from memory, cannot be
modified anymore... */
Or just overload your own delete operator:
struct students
{
string name;
int agee;
void students::operator delete ( void* ptr ) {
std::free(ptr);
ptr = nullptr; // Stop memory leaking...
}
};
Related
I have created one Node object and the pointer named head is pointing to it. Then another pointer named newHead is created which points to the same object. Then I delete the memory by doing delete head and reassign head to a nullptr. However, this change is not reflected by the newHead pointer. From the attached code it is evident that newHead is not a nullptr and accessing the member value returns garbage value.
To understand this problem, I have already gone through this post which states that
Also note that you can delete the memory from any pointer that points to it
which is evidently not the case for the attached code below. Further I know that using smart pointers will definitely one way to resolve the issue, but in my application, I do need to use a raw pointer.
Any help in giving me an understanding of why is this happening and how to resolve it will be appreciated. Thank you.
#include <iostream>
using namespace std;
class Node {
public:
Node(int value) {this->value = value;}
int value;
Node* next = nullptr;
};
int main(int argc, char** argv) {
// create a node object
Node* head = new Node(5);
// another pointer pointing to head
Node* newHead = head;
// delete the object pointed to by head
delete head;
head = nullptr;
// check if newHead is nullptr
if (newHead == nullptr) {
std::cout << "newHead is a nullptr" << std::endl;
}
else {
std::cout << "Head is not a nullptr" << std::endl;
std::cout << "Node value is: " << newHead->value << std::endl;
}
return 0;
}
The two pointers were pointing to the same memory, the nullptr is not put in there instead of the deleted object.
head = nullptr; // this is not putting nullptr where the deleted object was!
This is why, newHead is not pointing to nullptr but to a released memory.
What you want is a Reference to pointer
// CPP program to demonstrate references to pointers.
#include <iostream>
using namespace std;
int main()
{
int x = 10;
// ptr1 holds address of x
int* ptr1 = &x;
// Now ptr2 also holds address of x.
// But note that pt2 is an alias of ptr1.
// So if we change any of these two to
// hold some other address, the other
// pointer will also change.
int*& ptr2 = ptr1;
int y = 20;
ptr1 = &y;
// Below line prints 20, 20, 10, 20
// Note that ptr1 also starts pointing
// to y.
cout << *ptr1 << " " << *ptr2 << " "
<< x << " " << y;
return 0;
}
Output:
20 20 10 20
Credit to geeksforgeeks
In contrast, having
int* ptr2 = ptr1;
int y = 20;
ptr1 = &y;
Gives
20 10 10 20
If you delete the memory pointed by one or more pointers, the pointer values don't change. You can test this by checking the value pointer before and after the execution of the delete statement.
There's no way to (without saving some meta information somewhere) to know how many or what pointers are still pointing to some memory buffer.
The approach followed by this class of objects (that get pointed to from different places) is to have a count of the number of pointers you still have pointing to the buffer. When you assing a new reference, you increment the pointer, and when you delete one reference, you decrement it, and, only when the count of reference pointers is about to reach 0, then you actually delete it.
It's not complicated to use this technique to implement dynamic classes like trees or more abstract. I used it to implement a string type, years ago, with a copy on write semantics that allowed you to save copying string contents on mostly readonly strings.
I have created one Node object and the pointer named head is pointing to it. Then another pointer named newHead is created which points to the same object. Then I delete the memory by doing delete head and reassign head to a nullptr. However, this change is not reflected by the newHead pointer. From the attached code it is evident that newHead is not a nullptr and accessing the member value returns garbage value.
Right. Nowhere in your code in your code to you change newHeads value, so it still has the same value it had before. Of course, it is an error to access the member value because the object no longer exists.
To understand this problem, I have already gone through this post which states that
Also note that you can delete the memory from any pointer that points to it
which is evidently not the case for the attached code below.
Why do you say that? That's exactly what happened in your code. You had two pointers that point to the same block of memory and you could have used either to free it. You used one of them, and it was freed.
Any help in giving me an understanding of why is this happening and how to resolve it will be appreciated. Thank you.
You never change the value of newHead, so it contains the same value it had before you called free. Only after you call free, that object no longer exists, so it's a useless garbage value.
It's not clear what you don't understand. After you free a block of memory, it is an error to access it. The solution is simple -- don't do that. After you do delete head;, both head and newHead point to memory that is no longer allocated. You set head to nullptr, but you don't change newHead's value, so it still points to where the memory used to be.
If you are going to use malloc or new, it is your responsibility to track the lifetimes of objects and not access them outside their lifetimes.
I'm doing some learning exercises in c++ and I ran into an interesting question. Take this sample program.
#include <string>
#include <iostream>
char* pointer1;
void temp() {
char* s1 = new char;
*s1 = 'z';
pointer1 = s1;
std::cout << *pointer1 << std::endl;
for (int i = 0; i < 90000; i++) {
// Waste some processor time.
}
}
int main() {
temp();
std::cout << *pointer1 << std::endl;
delete pointer1;
//delete &pointer1;
std::cout << *pointer1 << std::endl;
return 0;
}
When you run it it prints out 'z' twice then some random garbage. Which is what I expected. If you un-comment 'delete &pointer1' and comment out the first delete and run the program you get an invalid pointer error from the output. I'm assuming this is deleting the address and what's actually stored there is remaining.
My question is when calling 'delete pointer1' does it delete 'char* s1' or just the address to where ever the s1 is stored? When calling 'delete &pointer1' is the address being deleted but s1 still in memory?
The address that pointer1 points to has been allocated by new. Hence, it is correct, even necessary, to call delete on that address.
However, &pointer1 gives you the address where pointer1 itself is stored. And this memory block has not been allocated by new. Hence, it is strictly illegal to call delete on it, which is precisely what the error is telling you.
So, yes, delete pointer1 frees the memory that has been allocated by new previously. But no, delete &pointer1 doesn't do anything but being illegal.
Additionally, accessing memory you called delete on previously is undefined behavior. So, your second *pointer1 is also nothing you want to write in a program that you do not want to crash or, even worse, that gives you unpredictable results.
I just learned pointer and delete pointer in class for C++. I tried this code by my own
# include<iostream>
using namespace std;
int main(){
int num = 10;
int *p = new int;
p = #
cout << *p << endl;
delete p;
cout << num << endl;
return 0;
}
After deleting the pointer p, I cannot print the value of num. But if I delete p at the very end of the program, cout << num << endl; will give me 10. Anyone knows where I did run?
You first leaked a pointer
int *p = new int;
p = # // You just leaked the above int
then illegally deleted something you did not new
delete p; // p points to num, which you did not new
You have already received a couple of good answers that point out the mistake, but I read a deeper misunderstanding of the allocation and deallocation of heap vs stack variables.
I realised this has become a pretty long post, so maybe if people think it is useful I should put it as a community Wiki somewhere. Hopefully it clarifies some of your confusion though.
Stack
The stack is a limited and fixed size storage. Local variables will be created here if you don't specify otherwise, and they will be automatically cleaned up when they are no longer needed. That means you don't have to explicitly allocate them - they will start existing the moment you declare them. Also you don't have to deallocate them - they will die when they fall out of scope, loosely speaking: when you reach the end brace of the block they are defined in.
int main() {
int a; // variable a is born here
a = 3;
a++;
} // a goes out of scope and is destroyed here
Pointers
A pointer is just a variable, but instead of an int which holds a whole number or a bool which holds a true/false value or a double which holds a floating point, a pointer holds a memory address. You can request the address of a stack variable using the address operator &:
{
int a = 3, b = 4;
int* p = &a; // p's value is the address of b, e.g. 0x89f2ec42
p = &b; // p now holds the address of b, e.g. 0x137f3ed0.
p++; // p now points one address space further, e.g. 0x137f3ed4
cout << p; // Prints 0x137f3ed4
} // Variables a, b and p go out of scope and die
Note that you should not assume that a and b are "next to" each other in memory, or that if p has a "used" address as its value then you can also read and write to the address at p + 1.
As you probably know, you can access the value at the address by using the pointer indirection operator, e.g.
int* p = &a; // Assume similar as above
*p = 8;
cout << a; // prints 8
cout << &a << p; // prints the address of a twice.
Note that even though I am using a pointer to point at another variable, I don't need to clean up anything: p is just another name for a, in a sense, and since both p and what it points to are cleaned up automatically there is nothing for me to do here.
Heap
The heap memory is a different kind of memory, which is in theory unlimited in size. You can create variables here, but you need to tell C++ explicitly that you want to do so. The way to do this is by calling the new operator, e.g. new int will create an integer on the heap and return the address. The only way you can do something sensible with the allocated memory, is save the address this gives you. The way you do this, is store it in a pointer:
int* heapPtr = new int;
and now you can use the pointer to access the memory:
*heapPtr = 3;
cout << heapPtr; // Will print the address of the allocated integer
cout << *heapPtr; // Will print the value at the address, i.e. 3
The thing is that variables created on the heap will keep on living, until you say you don't need them anymore. You do that by calling delete on the address you want to delete. E.g. if new gave you 0x12345678 that memory will be yours until you call delete 0x12345678. So before you exit your scope, you need to call
delete heapPtr;
and you will tell your system that the address 0x12345678 is available again for the next code that comes along and needs space on the heap.
Leaking memory
Now there is a danger here, and that is, that you may lose the handle. For example, consider the following:
void f() {
int* p = new int;
}
int main() {
f();
cout << "Uh oh...";
}
The function f creates a new integer on the heap. However, the pointer p in which you store the address is a local variable which is destroyed as soon as f exits. Once you are back in the main function, you suddenly have no idea anymore where the integer you allocated was living, so you have no way to call delete on it anymore. This means that - at least for the duration of your program - you will have memory that according to your operating system is occupied, so you cannot use it for anything else. If you do this too often, you may run out of memory even though you can't access any of it.
This is one of the errors you are making:
int* p = new int;
allocates a new integer on the heap and stores the address in p, but in the next line
p = #
you overwrite that with another address. At this point you lose track of the integer on the heap and you have created a memory leak.
Freeing memory
Aside from freeing memory not often enough (i.e. not instead of once), the other error you can make is freeing it too often. Or, to be more precise, you can make the error of accessing memory after you have told your OS you don't need it anymore. For example, consider the following:
int main() {
int* p = new int;
*p = 10;
delete p; // OK!
*p = 3; // Errr...
}
That last line is very wrong! You have just returned the memory allocated when you called delete, but the address is still stored in p. After you call delete, your OS is allowed to re-allocate the memory at any time - for example, immediately after another thread could call new double and get the same address. At that point, if you write *p = 3 you are therefore writing to memory that is no longer yours which may lead to disaster, if you happen to overwrite the location in memory where the nuke's launch codes are stored, or nothing may happen at all because the memory is never used for anything else before your program ends.
Always release your own memory, and nothing but your own memory
We have concluded the following: memory allocated on the stack is not yours to claim, and not yours to release. Memory allocated on the heap is yours to claim, but you must also release it once and only once.
The following examples are incorrect:
{
int a = 3;
int* p = &a;
delete a;
} // Uh oh... cannot clean up a because it is not ours anymore!
{
int* p = new int;
delete p;
*p = 3; // Uh oh, cannot touch this memory anymore!
delete p; // Uh oh, cannot touch this memory anymore!
}
Why does it print 10?
Well, to be honest, you were just "lucky" there. Actually, the way your operating system manages memory, is generally pretty lazy. When you tell it "I would like some memory" it doesn't zero it for you. That is why it is a bad idea to write
int main() {
int a;
a = a + 3;
cout << a;
}
You get allocated a variable a somewhere in the memory, but the value of a will be whatever was in that memory location. It might be zero, or some random number that depends on how the bits fell when you booted your computer. That is why you should always initialize the variable:
int a = 0;
Similarly, when you say "I don't need this memory" anymore, the OS doesn't zero it. That would be slow and unnecessary: all it needs to do is mark the memory as "free to be re-allocated". So if you give it back and access it immediately afterwards, the probability that it has not been re-allocated yet is pretty large. Therefore
int* p = new int;
*p = 10;
delete p;
cout << *p;
is not guaranteed to print 10. The address p is pointing to may have been (partially) taken (and initialized!) by someone else immediately after the delete. But if it hasn't, the memory will still contain the value 10 there so even though it isn't yours anymore, C++ will still allow you to access it. Basically, when you are using pointers, you are telling it "trust me, I'm a programmer - you don't need to do all kinds of slow checks to make sure I'm staying where I'm supposed to be, instead I'll be careful about that myself!"
using namespace std;
int main(){
int num = 10; // a) an int is created on stack
int *p = new int; // b) another int is allocated on heap
p = # // c) address of int from stack is assigned to p and the pointer
// allocated in b) is leaked: as nothing points to it anymore,
// it can't be deleted
cout << *p << endl;
delete p; // d) deleting a pointer that was not dynamically allocated
// and is pointing to stack.
cout << num << endl;
return 0;
}
I have a pointer which equals to another pointer
I'd like to check if my pointer equals to a pointer which is not null.
int* ptr0 = new int(5);
int* ptr1 = ptr0;
delete ptr0;
if ( ?? )
{
std::cout << "ptr1 equals to a null ptr" << std::endl;
}
What should I write in the condition ?
Knowing that:
I don't want to set nullptr any of the ptr's after removal
I don't have access to ptr0 in my condition
Use a shared_ptr<T> combined with a weak_ptr<T>.
For example,
int main() {
std::tr1::shared_ptr<int> ptr0(new int);
std::tr1::weak_ptr<int> ptr1_weak(ptr0);
*ptr0 = 50;
// Depending on if you reset or not the code below will execute
//ptr0.reset();
if (std::tr1::shared_ptr<int> ptr1 = ptr1_weak.lock()) {
std::cout << "Changing value!" << std::endl;
*ptr1 = 500;
}
}
You can't. While in theory you could, depending on the implementation of new, check if the memory pointed to is currently in use there's no way to confirm that it's still the same object you were originally pointing to using only raw pointers.
You can use C++11 smart pointers to do something kinda like that, but I really don't think that's what you actually wanna do here.
delete does not result in a null pointer. It results in a dangling pointer, which is undetectable in general. So, you cannot.
Given the following code:
void Allocate(int *p)
{
p = new int;
*p++ = 2;
}
int main()
{
int i = 10;
Allocate(&i);
std::cout << i << std::endl;
}
I'm a bit confised about the meaning of:
*p++ = 2;
The output is 10 and my reasoning as to why this is the case is that *p++ is a temporary therefore any assignment to it is lost at the end of the scope of Allocate(int *p).
Is this the case?
Thanks in adv!
On input to Allocate, p points to the variable i in the main
function.
The address of this variable then lost and replaced by the
new int.
The value of this int (which is uninitialized and so could
start as anything) is set to 2.
The p pointer is incremented.
The Allocate function returns at this point, leaking the int that was
allocated.
The value of i in the main function is unchanged,
because Allocate did not modify it.
when you pass the the address of i into Allocate, another (temp) pointer is created that points to i's address (i.e. passing by pointer). then that temp pointer is pointed to a new location (via new int). thus the value of i is left alone.
p = new int;
You're assigning p new memory to point to instead of what it was pointing to before. You then change this newly allocated memory and it's lost forever when the function ends, causing a memory leak. If you remove the allocation line, it should cause an output of 2. The ++ does nothing in this case. It just increments the pointer and returns the old value to dereference.
As soon as you enter Allocate, you assign p to point to a new block of memory, so it no longer points to i. Then you modify that new block of memory (which is then leaked when the method returns.) i is unaffected because you've moved that pointer before you set the pointed-to memory cell.
void Allocate(int **p)
{
*p = new int;
**p = 2;
}
int main()
{
int j = 10;
int *i = &j;
std::cout << i << std::endl;
Allocate(&i);
std::cout << i << std::endl;
}
Output is :
10
2
You need a pointer to pointer to change the address of the location being pointed to.