(visual)c++ 内存分配

“烫”和“屯”

在vc++中,栈中未初始化的内存在变量监视窗口总是显示为一串“烫”字;而堆中未初始化的内存则显示一串“屯”字。

原因是:vc++编译器对栈中未初始化的内存默认设置为0xcc,而两个0xcc,即0xcccc在GBK编码中就是“烫”;而堆中未初始化的内存默认设置为0xcd,而0xcdcd在GBK编码中则是“屯”。

内存分配方式

程序运行时,首先要被加载到内存,程序在内存中的布局大致如下图:

代码区存放程序的执行代码。

数据区存放全局数据、常量、静态变量,所以在c++中数据区又可分为自由存储区(自由存储区是那些由malloc等分配的内存块,它和堆十分相似,不过它是由free来释放的)、全局/静态存储区、常量存储区。

堆区提供动态内存,供程序随机申请。程序员通过new操作符从堆上申请内存,通过delete操作符释放动态申请的堆内存。如果由new动态申请的内存在使用完之后没有释放,则此块内存无法再次分配,这种情况称之为内存泄露(memory leak)。没有释放的堆内存,直到整个程序结束运行之后,由操作系统自动回收。

栈区存放局部数据,如函数参数、函数内的局部变量等。函数执行结束时,局部数据占用的栈内存被自动释放。栈是机器系统提供的数据结构,计算机会在底层对栈提供支持:它会分配专门的寄存器(如SP)存放栈的地址,而且压栈出栈由专门的指令来执行,所以对栈的操作效率会比较高。但是栈区的容量有限。

四个区中,除代码区之外的三个区都可以在编程中由程序员控制使用。

堆与栈的区别

(1)堆内存在使用时由程序员负责申请和释放,栈内存由编译器自动管理。

(2)在32位系统下,堆内存可以达到4G,基本无限制。栈内存有大小限制且通常很小,比如vc++编译器默认的线程栈大小为1M。

(3)对于堆内存,频繁申请释放会造成内存空间不连续,产生内存碎片使程序效率降低。栈则不会。

(4)堆内存地址向上(高地址方向)生长,栈内存地址向下生长。

(5)栈内存分配和操作效率高于堆内存。

vc++编译器设置堆栈大小

以vc2008为例,Properties->Linker->System->Heap Reserve SizeHeap Commit SizeStack Reserve SizeStack Commit Size。msdn中关于此4个参数的解释如下:(此4个参数设置为0,表示使用默认值)

/HEAP:reserve[,commit]

  The /HEAP option sets the size of the heap in bytes. This option is only for use when building an .exe file.

  The reserve argument specifies the total heap allocation in virtual memory. The default heap size is 1 MB. The linker rounds up the specified value to the nearest 4 bytes.

  The optional commit argument is subject to interpretation by the operating system. In Windows NT/Windows 2000, it specifies the amount of physical memory to allocate at a time. Committed virtual memory causes space to be reserved in the paging file. A higher commit value saves time when the application needs more heap space, but increases the memory requirements and possibly the startup time.

/STACK:reserve[,commit]

  The /STACK option sets the size of the stack in bytes. Use this option only when you build an .exe file.

  The reserve value specifies the total stack allocation in virtual memory. For x86 and x64 machines, the default stack size is 1 MB. On the Itanium chipset, the default size is 4 MB.

  commit is subject to interpretation by the operating system. In Windows NT and Windows 2000 it specifies the amount of physical memory to allocate at a time. Committed virtual memory causes space to be reserved in the paging file. A higher commit value saves time when the application needs more stack space, but increases the memory requirements and possibly the startup time. For x86 and x64 machines, the default commit value is 4 KB. On the Itanium chipset, the default value is 16 KB.

【学习资料】 《编写高质量代码 c++》

posted on 2013-03-18 14:38  zhuyf87  阅读(1243)  评论(0编辑  收藏  举报

导航