Search code examples
c++pointersmemory-managementdynamic-memory-allocation

c++ pointer always on the same address even if not deleted


I am playing with C++ pointers. I allocated memory to a pointer but I didn't free it afterwards. The next time I ran the program the pointer resides on the same address - why? Shouldn't OS see that address as occupied thus generating a memory leak?

int* a = new int[1]; //or (int*) malloc(1);
cout << &a << endl; //always 0x28fe98

Solution

  • A few misunderstandings...

    1. The expression &a is the address of the variable a, that is, the address of the pointer, of type pointer-to-pointer-to-int. It does not matter the value of a itself, that is, whether it is initialized or not, its address is the same. You probably want to do cout << a << std::endl;

    2. For each run of the program the OS allocates a whole new address space, and frees it when the program finishes, so even if you don't free the memory it will be freed when the program finishes. And even if the program does not finish, each process has its own address space, so the memory allocated in one does not affect the memory of the other.

    3. It is only natural that several runs of the same program yields more or less the same addresses, unless some form of virtual space randomization is used (for security purposes).

    Anyway, remember that in C++ there are basically 3 types of memory: static (global variables), automatic (local variables) and dynamic (new'ed objects). In your example, a (with address &a) is automatic or static, not clear from the context, but the integer pointed to by a (address a) is dynamic. You may want to play with all 3 of them to see how they are different.

    A particularly interesting experiment is the address of a local variable in a recursive function:

    void rec(int x)
    {
        cout << x << ": " << &x << endl;
        if ( x > 0)
            rec(x - 1);
    }