int *a;
if (true)
*a = 2;
else
*a = 3;
As you see, a
is not a dynamically allocated pointer. Should I assign it to nullptr
before exiting? Does unique_ptr
do for me automatically? What about the memory pointer to by a
? If I null a
before it goes out of scope, will it cause a memory leak?
CodePudding user response:
int *a; if (true) *a = 2;
The behaviour of this program is undefined. a
does not have a valid pointer value, so you may not indirect through.
Should we NULL every raw pointer after it is used?
It depends. For example, if the lifetime of the pointer is about to end, then it's redundant to assign it to null.
Does unique_ptr do for me automatically?
unique_ptr isn't a raw pointer.
But no, unique_ptr cannot know whether you've stopped using it or not, so it cannot set itself to null when you've stopped using it.
If I null a before it goes out of scope, will it cause a memory leak?
There is no difference between setting a pointer null, and not setting it to null before the pointer goes out of scope.