Memory layout of c program, about the location of local variable and global varible

413 Views Asked by At

Some books and web pages told me knowledge about memory layout of a C program. Such as stack locates at higher addresses than heap, global variables locate lower than stack. But I find this is not true:

D:\code>type testlayout.cpp

#include <stdio.h>

int g;


int main()
{
    int loc = 0;
    printf("%p %p\n", &g, &loc);
}

D:\code>cl testlayout.cpp

Microsoft (R) C/C++ Optimizing Compiler Version 17.00.61030 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

testlayout.cpp
Microsoft (R) Incremental Linker Version 11.00.61030.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:testlayout.exe
testlayout.obj

D:\code>testlayout.exe

000000013F2222C0 000000000022FB20

D:\code>

Can anyone explain why the address of the global variableis larger than the address of the local variable.

2

There are 2 best solutions below

1
On

The memory layout of a c (or c++) program is not defined by the c (or c++) standard. Your books are lying out of ignorance or perhaps they've actually said that is a typical memory layout or a layout which is true for a program produced by a particular compiler on a particular platform which is not necessarily same as yours. Since the layout is not defined, different compilers on different platforms may use any memory layout they find practical.

Your program is c++ rather than c though, so if such layout was defined for c, it wouldn't necessarily apply to your program.

0
On

Neither the C nor C++ standard has ever specified where objects are to be placed in memory. They definitely don't say anything about where the memory segments are, relative to each other. (In fact, some architectures don't even store their code and data in the same memory space at all!)

While your book's statement may be true for some OSes and architectures, it is by no means true for all of them. Modern address space randomization may further muddy the picture by placing the stack, program and heap addresses randomly.