Friday, February 19, 2016

[C++] Heap and stack in memory

A C++ compiler will use the fallowing parts :

1 stack:  methods' parameter name, local variable name, FIFO, Allocat/ free by compiler
2 heap:  new objects, alloc/free by programmer
3 static(global) : global variable and static variable
4 const string
5 function body

int global_1=1000;//静态变量 外部链接性 常量表达式 初始化
int global_2;//静态变量 外部链接性 零 初始化
static int one_file_1=1000;//静态变量 内部链接性 常量表达式 初始化
static int one_file_2;//静态变量 内部链接性 零 初始化
int main()
{
static int count_1=1000;//静态变量 无链接性 常量表达式 初始化
static int count_2;//静态变量 无链接性 零 初始化
return 0;
}


//main.cpp   
  int   a   =   0;   全局初始化区   
  char   *p1;   全局未初始化区   
  main()   
  {   
  int   b;   stack    compilation
  char   s[]   =   "abc";   stack compilation   
  char   *p2;   stack, compilation for the symble 
  char   *p3   =   "123456";   123456/0 on const string ,p3 is on stack, compilation   
  static   int   c   =0;   Static  compilation
  p1   =   (char   *)malloc(10);  heap    run time
  p2   =   (char   *)malloc(20);    heap run time
  分配得来得10和20字节的区域就在堆区。   
  strcpy(p1,   "123456");  
123456/0 on const string , compiler may optimize it to the same place as thep3's string in the const String.
  }    


using stack (A a(5)) is more easy cause the compiler will manage the malloc/free,
using heap (A* a=new A(5)) is more powerful but we should manage the malloc/free(new/delete).



http://www.cnblogs.com/hanyonglu/archive/2011/04/12/2014212.html

No comments:

Post a Comment