1. C程序的存储空间布局:
C 程序由下面几个部分组成:
- 正文段(即是代码段):
这是由CPU执行的机器指令部分。通常,正文段是可以共享的,并常常是可读的,以防止程序因为意外原因而修改自身的代码! - 初始化数据段(即数据段): 它包含了程序中需要明确的赋初值的变量。
- 非初始化数据段(bss段):在程序开始执行之前,内核将此段中的数据初始化为0或空指针。
- 栈。自动变量以及每次函数调用时所需保存的信息都存放在此段中。每次调用函数时,返回地址以及调用者的环境信息(如某些寄存器的值)都存放在栈中。然后,最近被调用的函数在栈上为其自动和临时变量分配存储空间。这样可以实现函数的递归调用!
- 堆。通常在堆中进行动态存储分配!
我们现在来做个实验来验证上述说法是否正确:
我们现在来编写一个Base程序,这个程序的main函数中没有自动变量,main函数的外部也没有非初始化数据;
1 #include <stdio.h>
2
3 int main(void)
4 {
5 return 0;
6 }
我们编译上述程序的到Base的可执行程序,然后用size命令观察各个程序段的大小:
size Base
text data bss dec hex filename
1115 552 8 1675 68b Base
下面我们在Base程序的main函数中增加一些初始化的变量:
1 #include <stdio.h>
2 int arr[1000] = {1};
3 int main(void)
4 {
7 return 0;
8 }
size Drive1
text
data
bss
dec
hex filename
1115
4568 8
5691 163b Derive1
可见在mian函数之外增加了int
arr[1000] = {1}; 语句之后data段增加4016byte!
1 #include <stdio.h>
2
3 int arr[1000];
4
5 int main(void)
6 {
7 return 0;
8 }
结果是:
text data bss dec hex filename
1115 552 4032 5699 1643 Derive1
bss段增加了4024!
2. 存储器的分配:
函数原型:
NAME
malloc, free, calloc, realloc - allocate and free dynamic memory
SYNOPSIS
#include <stdlib.h>
void *malloc(size_t size);
void free(void *ptr);
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);
函数说明:
The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initial‐
ized(malloc分配出来的空间并未被初始化). If size is 0, then malloc() returns either NULL, or a unique pointer value that can later
be successfully passed to free().
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to mal‐
loc(), calloc() or realloc().(free函数只能释放动态分配的空间)
Otherwise, or if free(ptr) has already been called before, undefined
behavior occurs. If ptr is NULL, no operation is performed.
The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the
allocated memory. The memory is set to zero.(callo函数分配出来的空间会被初始化)
If nmemb or size is 0, then calloc() returns either
NULL, or a unique pointer value that can later be successfully passed to free().
The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be
unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is
larger than the old size, the added memory will not be initialized. If ptr is NULL, then the call is equivalent to
malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to
free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc(). If
the area pointed to was moved, a free(ptr) is done.
下面是《The C Programming Language》中关于内存分配管理的一个实例:
进程篇(2: C程序的存储空间布局)--请参照本博客“操作系统”专栏