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.
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.