1

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 = &num;
    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?

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
Serena Qi
  • 121
  • 1
  • 3
  • 11

3 Answers3

12

You first leaked a pointer

int *p = new int;
p = &num;  // 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
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • And in addition, you tried to read a variable which you just `delete`d. It's great that your system is lazy in cleaning up the memory so you _accidentally_ still get the right value, but you should _not_ be accessing memory that you just released! – CompuChip Nov 20 '15 at 15:11
  • 2
    @CompuChip he de-referenced before deleting – Minato Nov 20 '15 at 15:12
  • I thought I `new` the pointer `p` and then let it point it to `num`..Maybe I can just: `int *p = new int; *p = num;`? – Serena Qi Nov 20 '15 at 15:15
  • What you're doing *is* making `p` point to `num`. That makes your program wrong. The code you now posted is however valid. – LogicStuff Nov 20 '15 at 15:25
  • @SerenaQi what you need is `int* p = &num` -- no `new` and no `delete`. – CompuChip Nov 20 '15 at 21:38
3

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 = &num;

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!"

CompuChip
  • 9,143
  • 4
  • 24
  • 48
  • Thanks a lot! A deep and thorough clarification of pointers and memory! My uni should hire you to teach! – Serena Qi Nov 21 '15 at 00:22
1
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 = &num;          // 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;
}
Zdeslav Vojkovic
  • 14,391
  • 32
  • 45