首页 > 技术知识 > 正文

经典的Linux进程内存布局,如下图:

浅谈C语言中数组在内存的存在形式-c语言数组过大怎么办

整个内存空间包括栈区,全局区,堆区。

复制void arr_on_stack() { int arr[6]; arr[0]=100; arr[1]=200; arr[2]=300; arr[3]=400; arr[4]=500; arr[5]=600; int a = arr[0]; }

我们定义了一个局部变量arr作为int类型的数组,然后分别将100-600写到了数组中。那么,数组arr在内存中是怎样表示的呢?

首先,我们编译一下:

复制#gcc-g-fno-stack-protectora.c

注意,-fno-stack-protector选项是为了禁止堆栈保护,让汇编更容易懂些。使用gdb测试代码运行情况,gdb面前程序的运行时(run time)了无秘密。用gdb来调试刚刚编译出来的程序,这里看一下arr_on_stack函数的汇编指令:

复制(gdb) disassemble arr_on_stack Dump of assembler code for function arr_on_stack: 0x0000000000400526 <+0>: push %rbp 0x0000000000400527 <+1>: mov %rsp,%rbp 0x000000000040052a <+4>: movl $0x64,-0x20(%rbp) 0x0000000000400531 <+11>: movl $0xc8,-0x1c(%rbp) 0x0000000000400538 <+18>: movl $0x12c,-0x18(%rbp) 0x000000000040053f <+25>: movl $0x190,-0x14(%rbp) 0x0000000000400546 <+32>: movl $0x1f4,-0x10(%rbp) 0x000000000040054d <+39>: movl $0x258,-0xc(%rbp) => 0x0000000000400554 <+46>: mov -0x20(%rbp),%eax 0x0000000000400557 <+49>: mov %eax,-0x4(%rbp) 0x000000000040055a <+52>: nop 0x000000000040055b <+53>: pop %rbp 0x000000000040055c <+54>: retq End of assembler dump. 浅谈C语言中数组在内存的存在形式-c语言数组过大怎么办1 审核编辑:汤梓红

猜你喜欢