0

Suppose I have a simple code something like that allocates a block of memory of a size of 4 byte and prints the address:

int32_t *ptr = malloc(4);
*ptr = 90; //for debugging
printf("%p\n", ptr);
//did not freed

Now when I execute this, (I executed it 6 times) I was confused to see an address get allocated twice:

$ ./t
0xb6cca008
$ ./t
0xb6cca008
$ ./t
0xb6d4a008
$ ./t
0xb6d8a008
$ ./t
0xb6d8a008
$ ./t
0xb6d0a008
$

And if try printing the value of the said address above, expecting to get 90, I instead get an annoying segmentation fault.

Code for accessing value of the address:

int32_t *ptr = (int32_t *) 0xb6cca008;
printf("%d\n", *ptr);

The remarkable thing here is the appearance of the address 0xb6cca008 and 0xb6d8a008 in a streak. I thought malloc don't use the same address?

And the problem might be in my side because I'm using termux, a linux terminal emulator inside android. I have never used a real PC with linux installed so I don't know if segmentation fault would appear or would print 90.

Since 4 byte is allocated on the heap and not freed after program terminates, shouldn't it exist and not give a segmentation fault? I also doubt that this is also an "Access violation".

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Spade 000
  • 109
  • 1
  • 11
  • 3
    The memory map and all pointers to heap-allocated objects is private to each process. Two processes, even running the same program, won't naturally share data. A pointer in one program is not valid in another. This is one of the basics of modern protected operating systems: Process separation. – Some programmer dude Jun 04 '20 at 17:00
  • Why do you think memory that is not freed remains allocated after program termination? – underscore_d Jun 04 '20 at 17:01
  • 2
    Furthermore, on all modern operating systems all resources that a process acquire will be released when the process exits. So your premises that heap memory allocated by one process will still be in memory once the process exits is false. – Some programmer dude Jun 04 '20 at 17:01
  • 1
    https://www.geeksforgeeks.org/ipc-shared-memory/ – Robert Harvey Jun 04 '20 at 17:04

1 Answers1

0

Modern operating systems on common CPUs (with some exceptions like some embedded systems) release the memory your process has mapped when the process finishes, whether you called free() or not. That means that even if there was a single address space, you could still see the same pointer in several runs.

Further, each process gets its own address space, which means several processes routinely share the same addresses. So you may have a pointer pointing to the same virtual address, but in reality they are pointing to a different physical address. This is called virtual memory.

Acorn
  • 24,970
  • 5
  • 40
  • 69