Reputation: 263
so basically I'm trying this code out, compiling in cl (visual studio C++ compiler) and it keeps printing 0. Shouldn't y be equal to nullptr?
#include <iostream>
#include <string>
using namespace std;
int main() {
int* x;
x = new int(5);
int* y;
y = x;
delete x;
x = nullptr;
cout <<(y==nullptr)<< endl;
return 0;
}
Upvotes: 0
Views: 81
Reputation:
A pointer is not "deleted". The delete operation deallocates the memory block pointed to by the pointer, and leaves this pointer unchanged. It is not set to nullptr
, and does not point to "nothing" (by the way, you are clearing it explicitly).
And a pointer behaves like an ordinary variable, holding a value (an address). Changing the value of a variable doesn't influence another (except in case of aliasing, but that's another story.)
Upvotes: 2
Reputation: 234705
No, setting x
to nullptr
does not set y
to nullptr
too.
y
is an int*
not a reference to an int*
.
So, y == nullptr
is necessarily1 false
.
1 For the pub quiz: x
cannot be nullptr
since if an allocation failed then std::bad_alloc
would have been thrown. It would be possible for y
to be nullptr
had you written x = new(std::nothrow) int(5);
Upvotes: 5
Reputation: 2943
What actually is happening here:
Upvotes: 0
Reputation: 8589
No.
Let's go line by line:
x = new int(5); //allocate an integer, set it to 5 and return a pointer to it (x will not nullptr).
int* y; //allocate local storage to another pointer.
y = x; //copy the (not nullptr) value of x into y.
delete x; //de-allocate the space previously allocated.
//At this point the value of x is unchanged and y is equal to it.
//De-referencing x (*x) however is undefined because it was deallocated.
x = nullptr; //Set x to nullptr. Has no effect on y.
cout <<(y==nullptr)<< endl; //y still equals the (now invalid) value allocated above.
Assigning a variable to another variable is one-time thing. After that changes to one will not be reflected in the other (though changes 'through' one may affect the other).
Upvotes: 0
Reputation: 2211
Pointers are still normal variables, with a right and a left value.
They are special only in the fact that their right value is an address of a memory location that can be managed by the user.
In your case, both x
an y
are allocated somewhere on the stack. Where you do y=x
you set the value of y
to be the same value of x
, but later, when you do x=nullptr
you only change the value of x
, not the value of y
.
Also, pay attention to the fact that while before delete x
both x
and y
refer to a valid address, after it x
is correctly set to a nullptr
, while y
retains the now invalid memory address. This is a case of pointer aliasing, which can give several problems, first of all invalid memory access errors.
Upvotes: 0