程序内部的结构是分段的,一般分为代码段、堆、栈、数据段等。可以通过下面的代码来证明:
#include <stdio.h>
int globalIntA=10;
void variableInStack()
{
printf("%s:%d:%s location is %p\n",__FILE__,__LINE__,__FUNCTION__,(void*)&__FUNCTION__);
printf("%s:%d:%s global globalIntA is %p\n",__FILE__,__LINE__,__FUNCTION__,(void*)&globalIntA);
int localIntB=100;
printf("%s:%d:%s local localIntB is %p\n",__FILE__,__LINE__,__FUNCTION__,(void*)&localIntB);
}
void variableInHeap()
{
printf("%s:%d:%s location is %p\n",__FILE__,__LINE__,__FUNCTION__,(void*)&__FUNCTION__);
char *description = malloc(10* sizeof(char));
if( description == NULL )
{
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else
{
strcpy( description, "IN HEAP");
}
printf("Description: %s\n", description );
printf("%s:%d:%s malloc description is %p\n",__FILE__,__LINE__,__FUNCTION__,(void*)&description);
printf("%s:%d:%s malloc *description is %p\n",__FILE__,__LINE__,__FUNCTION__,&(*description));
free((void*)description);
int localIntB=100;
printf("%s:%d:%s local localIntB is %p\n",__FILE__,__LINE__,__FUNCTION__,(void*)&localIntB);
static int stcIntC;
printf("%s:%d:%s static int stcIntC is %p\n",__FILE__,__LINE__,__FUNCTION__,(void*)&stcIntC);
}
int globalIntB;
int main(int argc, char ** argv)
{
printf("%s:%d:%s process begin @ %p\n",__FILE__,__LINE__,__FUNCTION__,(void*)&__FUNCTION__);
printf("%s:%d:%s global globalIntB is %p\n",__FILE__,__LINE__,__FUNCTION__,(void*)&globalIntB);
printf("====================\n");
variableInStack();
printf("====================\n");
variableInHeap();
return EXIT_SUCCESS;
}
程序的执行结果如下:
/Users/huGuohua/xcode/c_study/c_study/main.c:30:main process begin @ 0x100003f5e
/Users/huGuohua/xcode/c_study/c_study/main.c:31:main global globalIntB is 0x10000810c
====================
/Users/huGuohua/xcode/c_study/c_study/memoryAddress.h:18:variableInStack location is 0x100003e04
/Users/huGuohua/xcode/c_study/c_study/memoryAddress.h:19:variableInStack global globalIntA is 0x1000080d8
/Users/huGuohua/xcode/c_study/c_study/memoryAddress.h:21:variableInStack local localIntB is 0x7ffeefbff42c
====================
/Users/huGuohua/xcode/c_study/c_study/memoryAddress.h:26:variableInHeap location is 0x100003e56
Description: IN HEAP
/Users/huGuohua/xcode/c_study/c_study/memoryAddress.h:38:variableInHeap malloc description is 0x7ffeefbff428
/Users/huGuohua/xcode/c_study/c_study/memoryAddress.h:39:variableInHeap malloc *description is 0x10181e6b0
/Users/huGuohua/xcode/c_study/c_study/memoryAddress.h:42:variableInHeap local localIntB is 0x7ffeefbff424
/Users/huGuohua/xcode/c_study/c_study/memoryAddress.h:44:variableInHeap static int stcIntC is 0x100008108
Program ended with exit code: 0
根据以上的结果,可以发现如下规律:
函数的地址在一起,放在代码段的;
函数内部的变量的地址在一起,放在栈段的;
全局变量放在数据段,数据段中还会存放静态变量;
如果一块内存是用malloc创建的,那么它在堆中;
这就是内存中的进程的几个段:
代码段存放可执行代码、字符串常量、常量数据;
数据段存放已初始化全局变量、静态变量;
栈存放局部变量、函数参数;
堆是用来动态内存分配的;