Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference in the memory layout of Windows and Linux OS?

When I run the code written below on windows and on Linux, I get different output for the two.

I am using gcc for both. When I run it on windows, I get "Seek" as output whereas running it on Linux, I am getting "Hide" as the output. Is there any difference in the memory layout of Windows and Linux, or is there something else which causes the output to differ?

int main()
{
    int a=0;
    int *b=(int *)malloc(sizeof(int));
    if(&a>b)
        printf("Hide");
    else
        printf("Seek");
    return 0;
}
like image 318
Lalit Agarwal Avatar asked Jul 27 '12 12:07

Lalit Agarwal


People also ask

What is memory layout in Linux?

The 4 GB address space in 32 bit x86 Linux is usually split into different sections for every process on the system: 0GB-1GB User space - Used for text, code and brk / sbrk allocations. malloc uses brk for small chunks. 1GB-3GB User space - Used for shared libraries, shared memory, and the stack.

What does Linux have that Windows doesn t?

Linux is an open source operating system whereas Windows OS is commercial. Linux has access to source code and alters the code as per user need whereas Windows does not have access to the source code. In Linux, the user has access to the source code of the kernel and alter the code according to his need.

What is memory layout OS?

The computer memory is built to store bit patterns. Not only data but also instructions are bit patterns and these can be stored in memory. In systems software, they are stored in separate segment of memory. And the segments are also divided by data and program type. The multitasking OS runs in virtual address space.

What memory management does Windows use?

The Windows kernel-mode memory manager component manages physical memory for the operating system. This memory is primarily in the form of random access memory (RAM).


1 Answers

Yes, windows and linux lay out their memory differently. Some examples are here. For example, windows typically splits your memory evenly (in 32-bit) between kernel and user space, while linux is 3/1 user/kernel.

The compiler can also lay out the memory as it sees fit, within the limits of the spec. This means that the llvm compiler, gcc, and ever different versions of these can have different output.

Optimizations can also change layout, and even remove some variables that aren't strictly needed.

Also, even if memory was allocated low to high, after some other memory was freed a new allocation could come from the previously used area and be low again.

Short answer: expecting memory layout/location between unrelated variables is not a good idea.

like image 102
Paul Rubel Avatar answered Oct 03 '22 21:10

Paul Rubel