0
点赞
收藏
分享

微信扫一扫

编程基础 之 Stack和Heap的区别

Stack和Heap在哪儿

都在RAM,即都在内存中存放

Stack

在一个函数被调用时候,在stack会保留一块以用来保存local variables。函数返回时,这块stack成为Unuse的状态,提供给下一个函数的使用。

function func(){
  int i = 1; // Allocated on stack
} // De-allocated from stack

function func1(){
  int j = 2; // Allocated on stack
}// De-allocated from stack


void main(){
  func();
  func1();
}

Heap

Heap的分配和释放比较自由,可以随时分配,并且随时释放。

new 和 malloc创建的东西将会存放到Heap中,属于dynamic allocation

function func(){
  int i = 1; // Allocated on stack
  Char* buffer = new Char[20]; // Allocated on heap
  doSomething;
  deallocated buffer; //deallocated from heap
  doSomethingElse;
}//deallocated from stack

Thread中的Stack和Heap的关系

每个thread都有自己的Stack,同一process下的Threads之间共享一个Heap。

例子

Stack和Heap的分配

int i = 1; // Allocated on stack
Char* string = "Vigor"; //Allocated on stack
Char* buffer = new Char[20]; // Allocated on heap

int foo()
{
  char * pBuffer;
  //<--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack).
  bool b = true;
  // Allocated on the stack.
  if(b)
  {
    //Create 500 bytes on the stack
    char buffer[500];

    //Create 500 bytes on the heap
    pBuffer = new char[500];

   }
   //<-- buffer is deallocated here, pBuffer is not
} //<--- oops there's a memory leak, I should have called delete[] pBuffer;

使用Stack和Heap时常见的问题

Stack的分配和释放是受到Compiler的控制,同时,Heap的分配和释放是受到Developer的控制(C和C++),所以说Heap的问题出现的会比Stack的问题多

分配时的问题

  • 没有分配heap
  • 分配不足的heap

释放时的问题

  • 忘记释放Heap
  • 释放多次Heap
  • 过早释放Heap,即,在没有完任务就释放Heap

Reference

https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap


想要看到更多玮哥的学习笔记、考试复习资料、面试准备资料?想要看到IBM工作时期的技术积累和国外初创公司的经验总结?

敬请关注:

玮哥的博客 —— CSDN的传送门

玮哥的博客 —— 简书的传送门

玮哥的博客 —— 博客园的传送门

举报

相关推荐

0 条评论