-1

I'm curious and want to know if the pointer will still be hanging around pointing to an address even after the program ends.

I was taught that we should always set a pointer to null after deallocating its memory like this:

int* num = new int(2);

// do something with num

delete num;
num = nullptr;

But what if my pointer was not pointing to an address in dynamic memory but instead it is pointing to a common address in the stack for example:

int num = 2;
int* pnum = #

// do something with pnum

then should I also set the pointer to null? since I don't want it to keep pointing to an address

pnum = nullptr;

And if I don't set it to null will it still be pointing to that address once my program is done running?

I was taught to always set my pointer to null in dynamic memory use case but what about the pointers that point to common stack memory addresses?

EDITH for all those emotional guys in the comments yea im a 20y/o noobie still learning and yes you are so smart no one can deal with your iq cause your so smart hahaha. Stop dissing me nor the others trying to help. To all those giving simple logic explanations i appreciate you.

  • its a readability thing and a "signature" to say "yep I'm done with this" - nothing will outlive your process... – Daniel A. White Jun 21 '23 at 18:57
  • 1
    Once your program is done running the pointer also ceases to exist. It no longer points anywhere. – Nathan Pierson Jun 21 '23 at 18:57
  • My rule is if the pointer is no longer going to be used for anything, it can just be ignored. However, if the pointer will be used later on, I'd do the `p = nullptr;` so that later on the code is aware that `p` is not pointing to anything. – Eljay Jun 21 '23 at 19:01
  • Why are you explicitly allocating (and therefore deallocating) memory? – Paul Sanders Jun 21 '23 at 19:01
  • The issue with setting pointers to null is one where it won't have any effect. For example: `void foo(int *x) { ...delete x; x = nullptr; }` -- That does not change the value of the pointer passed to function`foo` -- yes, `delete` is issued, but the pointer passed in will still have the same value it was called with. – PaulMcKenzie Jun 21 '23 at 19:08
  • Setting a pointer to null is a **convention** to indicate that the pointer doesn't point at anything useful. If you don't need to make that decision, there's no reason to set the pointer to null. One fairly common example is a destructor that does `delete my_ptr; my_ptr = null;`. There's no reason whatsoever for setting that pointer to null. When the destructor has finished the object no longer exists, and no code can sensibly use `my_ptr`. – Pete Becker Jun 21 '23 at 19:20
  • "After the program ends" it does not matter either way. Doing something because you were taught to do so, without understanding the reason for the advice is _"cargo cult programming_" and no substitute for understanding _why_. – Clifford Jun 21 '23 at 19:20
  • *'I was taught to always set my pointer to null in dynamic memory'* that's debateable advice that you seem to have learned entirely the wrong lesson from. If you don't use a pointer it matters not all what it points to. No different from an integer. it doesn't matter if an `int` variable is 10, 100 or 1.000.000 if you don't use the variable. – john Jun 21 '23 at 19:23

1 Answers1

5

You don't need to set the pointer to null in either case. You only do it as a safety mechanism, so you don't accidentally try to read through an invalid pointer later (if the pointer is null, and you try to use it you'll die quickly and see the problem, if it's pointing to freed or otherwise no longer valid memory, the access might "work" by accident), nor cause damage if you delete it again (it's a legal no-op to call delete on a null pointer, but calling it twice on any other pointer will do terrible things).

Basically, if you're programming defensively like this, and the pointer variable might outlive what it's pointing to (e.g. the pointer is in global memory, and you give it the address of a stack variable that will disappear when the function returns), sure, null it out. Otherwise, there's no danger to leaving it populated, and only tiny benefits in specific cases to explicitly nulling it out (in practice, if it's not used again, an optimizing compiler might skip nulling it out even if you told it to do so, since there's no observable change from nulling a pointer that is never accessed again).

To be clear, in response to you "want to know if the pointer will still be hanging around pointing to an address even after the program ends", barring explicit persistence via stuff like memory mapped files or global shared memory (none of which applies in 99% of typical C & C++ code), all program memory is released when the program actually exits. It doesn't matter what the pointer was pointing to when the program exits, because the pointer itself ceases to exist at that point.

As a further note: The correct way to handle the occasional need for dynamically allocated memory like this is usually to avoid raw pointers entirely. From C++14 onwards, for the dynamically allocated case, your first example simplifies to:

auto num = std::make_unique<int>(2);

with no need to delete or null-out at all. Raw pointers would only be used in unmanaged cases like your stack case, or "lending" the raw pointer in a smart pointer for the duration of a function call (where the function accepts a raw pointer it doesn't intended to take ownership of), meaning your program can usually avoid using new or delete at all, and null-ing out pointers to avoid double-delete or use-after-free issues is no longer helpful (the smart pointer keeps it valid until the smart pointer gets destructed, at which point it's cleaned up exactly once).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • When the program exits Linux releases all memory used by the program. MS Windows does not, and this un-freeded memory stays some where (only MS and some hackers know). – Ripi2 Jun 21 '23 at 19:12
  • 2
    @Ripi2 *"MS Windows does not"* Huh? Citation needed. – HolyBlackCat Jun 21 '23 at 19:14
  • 1
    @Ripi2: I have no idea where you read that, but while there is a *tiny* grain of truth there (Windows and Linux have different strategies for zeroing out memory pages before providing them to a user mode program), you've overextended to the point of misunderstanding. The memory is freed, all of it. I could write a Windows program that allocated and filled in multiple gigabytes of data, and *never* called `delete`/`free`, and as soon as the program exited, that memory would go back to the OS for reuse, always. – ShadowRanger Jun 21 '23 at 19:16
  • I don't have such citation, I heared it many years ago. I did such program to test undeleted memory to be freeded by OS... and the "Tasks Manager" always showed increased memory use with each execution. Granted, I have not tested it with MSW>8 – Ripi2 Jun 21 '23 at 19:20
  • @Ripi2: The memory has been fully reclaimed on process exit since at *least* Windows 95 (Windows 3.11 and earlier were very different and I won't swear to anything on them). You misremembered, tested poorly, or the metrics shown in Task Manager were inaccurate (perhaps it might report memory from an exited program that has not been zeroed yet as "in use", but all that would mean is that, if *all* the existing zeroed pages got used up faster than they were background zeroed, memory allocations would go a little slower as it began needing to live-zero pages rather than pull pre-zeroed ones). – ShadowRanger Jun 21 '23 at 19:26
  • 1
    If it actually behaved the way you describe, new CS students would invariably crash their whole machine on the regular, not just their programs, as every toy program that leaked memory would permanently reduce the available memory until the next reboot. Think about this. Write a program that allocates a GB of memory, fills it with garbage (to ensure it's "really" allocated), and exits without freeing it. Run it a thousand times. If you manage to crash your box doing that, okay, you're right. Otherwise, the possibilities are: 1) You have over 1000 GB of memory, or 2) It got freed on exit. – ShadowRanger Jun 21 '23 at 19:30