首页 > 解决方案 > malloc() 到底是做什么的?

问题描述

为了更好地理解 malloc() 和 realloc() 我正在尝试运行以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
   char *str;

   str = malloc(20);
   str = strcpy(str, "inf110_malloc_test");
   printf("String = %s,  Address = %u\n", str, str);

   str = realloc(str, 25);
   str = strcat(str, " is dene perfectly.");
   printf("String = %s  Address = %u\n", str, str);

   free(str);
   return(0);
}

输出:

String = inf110_malloc_test,  Address = 1840192
String = inf110_malloc_test is dene perfectly.  Address = 1840192

问题是即使我将NULL参数传递给malloc().

...
str = malloc(NULL);
...

我在 cplusplus.com 上阅读了以下内容:

为避免溢出,destination 指向的数组的大小应足够长,以包含与 source 相同的 C 字符串(包括终止空字符),并且不应在内存中与 source 重叠。

为什么程序此时不会崩溃?strcpy()自动分配足够的内存吗?

标签: cstringmemory

解决方案


问题是即使我将NULL 参数传递给malloc().

这是未定义的行为,毫不犹豫。

realloc'ed 内存字段可以位于与malloc'ed one 相同的地址,也可以位于新的内存地址,但在数据移动后,空间充足。

因此,我会更好地理解,并更喜欢写作realloc(20 + 5)


推荐阅读