Magnus
Magnus

Reputation: 389

How is my pointer going to be handled be handled in C++ and Windows?

Is the following pointer always going to be NULL unless I don't set it pointing somewhere myself?

 int* mGlobal = NULL;

Or, could it be set by any other process or by Windows itself by some reason even if I have set it to NULL. Or is this pointer always going to be within my process protected memory as long as I am holding on to it?

And if I make an array of my pointer allocating some memory on the heap and then deletes it without setting it to NULL afterwards, then this address where it's pointing at will be free for any other process or Windows to use? Is there a difference between not setting or setting it to NULL after delete in this case?

The pointer itself will always be there as long as my process is holding on to it, but in what scenario will the memory my pointer is pointing at become changed by other processes or Windows while I'm still holding on to the pointer?

Many questions, I know.

Upvotes: 0

Views: 48

Answers (1)

codah
codah

Reputation: 468

Is the following pointer always going to be NULL unless I don't set it pointing somewhere myself?

Yes. The memory used by the pointer itself will not change. At the moment it's not pointing to anything as it is NULL. If you're using c++11, use nullptr.

And if I make an array of my pointer allocating some memory on the heap and then deletes it without setting it to NULL afterwards

If you allocate memory with new and later delete it, setting it to NULL or otherwise won't affect the memory it was pointing to before the delete. So no difference in that case, if I understand your question. But it's good practice to set it to NULL (nullptr). Better still use a smart pointer.

The pointer itself will always be there as long as my process is holding on to it

The pointer variable itself can change if you pass it as a reference or pointer and change it through that reference or pointer, but not normally otherwise. In the normal case, the memory it is pointing to can change via another pointer to the same memory. It will not normally be changed by other processes. It can be passed to other threads if you choose to do so. I have not considered esoteric cases.

as long as my process is holding on to it

Normally you won't think in terms of processes, or even threads, but scope. If the above variable is declared outside a class (as the name implies), then it has program scope. Such global variables are considered bad practice.

Upvotes: 1

Related Questions