c - 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()
自动分配足够的内存吗?
解决方案
问题是即使我将
NULL
参数传递给malloc()
.
这是未定义的行为,毫不犹豫。
realloc
'ed 内存字段可以位于与malloc
'ed one 相同的地址,也可以位于新的内存地址,但在数据移动后,空间充足。
因此,我会更好地理解,并更喜欢写作realloc(20 + 5)
。
推荐阅读
- c++ - C++ OpenGL:三角形不出现在屏幕上
- flutter - 通话后不保存数据颤动
- reactjs - 按钮 onclick 在 reactJS 中不起作用,代码如下
- java - 由于拦截器异常,Spring 写入中断响应
- raspberry-pi - 拔下局域网电缆时,Raspberry Wifi 失去连接
- android - 从 android studio 的内部存储中删除列表
- android - PendingIntent 存储在哪里?使用的大陷阱
- css - Firefox CSS 渲染问题
- python - discord_slash:如何实际添加斜线命令/为什么我的不起作用?
- python - Python moviepy 正在生成一个奇怪的视频