Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can malloc return same address in two different processes?

Suppose I have two process a and b on Linux. and in both process I use malloc() to allocate a memory,

Is there any chances that malloc() returns the same starting address in two processes? If no, then who is going to take care of this. If yes, then both process can access the same data at this address.

like image 800
beparas Avatar asked Dec 06 '22 13:12

beparas


2 Answers

Is there any chances that malloc() return same starting address in two process.

Yes, but this is not a problem.

What you're not understanding is that operating systems firstly handle your physical space for you - programs etc only see virtual addresses. There is only one virtual address space, however, the operating system (let's stick with 32-bit for now) divides that up. On Windows, the top half (0xA0000000+) belongs to the kernel and the lower half to user mode processes. This is referred to as the 2GB/2GB split. On Linux, the divide is 3GB/1GB - see this article:

Kernel memory is defined to start at PAGE_OFFSET,which in x86 is 0XC0000000, or 3 gigabytes. (This is where the 3gig/1gig split is defined.) Every virtual address above PAGE_OFFSET is the kernel, any address below PAGE_OFFSET is a user address.

Now, when a process switch (as opposed to a context switch) occurs, all of the pages belonging to the current process are unmapped from virtual memory (not necessarily paging them) and all of the pages belonging to the to-be-run process are copied in (disclaimer: this might not exactly be true; one could mark pages dirty etc and copy on access instead, theoretically).

The reason for the split is that, for performance reasons, the upper half of the virtual memory space can remained mapped to the operating system kernel.

So, although malloc might return the same value in two given processes, that doesn't matter because:

  1. physically, they're not the same address.
  2. the processes don't share virtual memory anywhere.

For 64-bit systems, since we're currently only using 48 of those bits there is a gulf between the bottom of user mode and kernel mode which is not addressable (yet).

like image 110
3 revs Avatar answered Dec 11 '22 12:12

3 revs


Yes, malloc() can return the same pointer value in separate processes, if the processes run in separate address spaces, which is achieved via virtual memory. But they won't access the same physical memory location in that case and the data at the address need not be the same, obviously.

like image 32
Alexey Frunze Avatar answered Dec 11 '22 10:12

Alexey Frunze