C++ memory layout(1)

TL;DR

  • 未初始化的全局变量储存在bss段
  • 未初始化的静态变量储存在bss段
  • 初始化的静态变量储存在data段(初始化为0还是在bss段)
  • 初始化的全局变量储存在data段(初始化为0还是在bss段)
  • 局部变量在程序运行时会在栈上分配空间,体现在text段里的初始化代码,所以初始化的局部变量会使的text段变大

#include<iostream>
using namespace std;

int main(){
    return 0;
}

long@DESKTOP-47UH3ST:~$ size ml
   text    data     bss     dec     hex filename
   1985     640       8    2633     a49 ml
#include<iostream>
using namespace std;

int global;

int main(){
    return 0;
}

long@DESKTOP-47UH3ST:~$ size ml
   text    data     bss     dec     hex filename
   1985     640      16    2641     a51 ml
#include<iostream>
using namespace std;

int global=0;

int main(){
    return 0;
}

long@DESKTOP-47UH3ST:~$ size ml
   text    data     bss     dec     hex filename
   1985     640      16    2641     a51 ml
#include<iostream>
using namespace std;

int global=1;

int main(){
    return 0;
}

long@DESKTOP-47UH3ST:~$ size ml
   text    data     bss     dec     hex filename
   1985     644       4    2633     a49 ml
#include<iostream>
using namespace std;

int main(){
    int local;
    return local;
}

long@DESKTOP-47UH3ST:~$ g++ ml.cpp -o ml && size ml
   text    data     bss     dec     hex filename
   1985     640       8    2633     a49 ml
#include<iostream>
using namespace std;

int main(){
    int local=0;
    return local;
}

long@DESKTOP-47UH3ST:~$ g++ ml.cpp -o ml && size ml
   text    data     bss     dec     hex filename
   2001     640       8    2649     a59 ml
#include<iostream>
using namespace std;

int main(){
    int local=1;
    return local;
}

long@DESKTOP-47UH3ST:~$ g++ ml.cpp -o ml && size ml
   text    data     bss     dec     hex filename
   2001     640       8    2649     a59 ml
#include<iostream>
using namespace std;

int main(){
    static int local;
    return local;
}

long@DESKTOP-47UH3ST:~$ g++ ml.cpp -o ml && size ml
   text    data     bss     dec     hex filename
   1985     640      16    2641     a51 ml
#include<iostream>
using namespace std;

int main(){
    static int local=0;
    return local;
}

long@DESKTOP-47UH3ST:~$ g++ ml.cpp -o ml && size ml
   text    data     bss     dec     hex filename
   1985     640      16    2641     a51 ml
#include<iostream>
using namespace std;

int main(){
    static int local=1;
    return local;
}

long@DESKTOP-47UH3ST:~$ g++ ml.cpp -o ml && size ml
   text    data     bss     dec     hex filename
   1985     644       4    2633     a49 ml
This entry was posted in showmecode. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.