Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do pointer / variable memory addresses not change?

Tags:

c++

#include <iostream>
using namespace std;

int main(void)
{
    int *ptr = new int;
    cout << "Memory address of ptr:" << ptr << endl;
    cin.get();
    delete ptr;

    return 0;
}

Every time I run this program, I get the same memory address for ptr. Why?

like image 652
Calvin Froedge Avatar asked Dec 24 '11 23:12

Calvin Froedge


1 Answers

[Note: my answer assumes you're working with a modern OS that uses a virtual memory system.]

Due to virtual memory, each process operates in its own unique address space, which is independent of and unaffected by any other process. The address you get from new is a virtual address, and is generated by whatever your compiler's implementation of new chooses to do.* There's no reason this couldn't be deterministic.

On the other hand, the physical address associated with your virtual memory address will most likely be different every time, and will be affected by all sorts of things. This mapping is controlled by the OS.


* new is probably implemented in terms of malloc.
like image 190
Oliver Charlesworth Avatar answered Sep 24 '22 09:09

Oliver Charlesworth