最近在学习 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() 时才分配内存。
本文深入探讨了在C语言中使用malloc函数申请内存时的细节,揭示了操作系统如何在实际使用内存时才进行分配的过程。通过具体代码实例,展示了malloc后的内存状态变化,包括strlen函数的应用、字符串复制和连接等操作对内存大小的影响。
2028

被折叠的 条评论
为什么被折叠?



