最近在学习 C 的字符串操作函数时偶然发现 malloc 分配内存时的细节,使用 malloc 语句申请内存后,操作系统不会立即分配相应的堆内存,而是在实际使用到这片内存时才分配。
如以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *prefix = "prefix";
char *ptr;
ptr = malloc(strlen(prefix)+4);
printf("strlen of prefix: %d\n",strlen(prefix));
printf("strlen of ptr: %d\n",strlen(ptr));
strcpy(ptr,prefix);
printf("strlen of ptr after strcpy: %d\n",strlen(ptr));
strcat(ptr,".bak");
printf("strlen of ptr after strcat: %d\n",strlen(ptr));
printf("%s\n",ptr);
free(ptr);
return 0;
}
执行上述代码结果如下:
strlen of prefix: 6
strlen of ptr: 0
strlen of ptr after strcpy: 6
strlen of ptr after strcat: 10
prefix.bak
可以看出,在执行了 malloc 语句后系统并没有给 ptr 分配内存,而是在执行 strcpy() 时才分配内存。