c - 为什么不重新分配额外内存就不会触发错误,C语言
问题描述
我是 C 语言新手,教程在这里。
我按照教程进行操作,但是当我尝试不重新分配内存时它不会出错,
无论是否注释 realloc 代码,结果都是相同的。
我想知道为什么?有人可以解释一下吗?谢谢
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char name[100];
char *description;
strcpy(name, "Zara Ali");
description = (char *) malloc(30 * sizeof(char));
if (description == NULL)
{
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else
{
strcpy(description, "Zara li a DPS student.");
}
// description = (char *) realloc(description, 100 * sizeof(char));
if (description == NULL)
{
fprintf(stderr, "Error - unable to allocate required memory\n");
}
else
{
strcat(description, "She is in class 10th.");
}
printf("Name = %s\n", name);
printf("Description: %s\n", description);
free(description);
}
结果:图片
解决方案
description
在您的代码中,您初始化
description = (char *) malloc(30 * sizeof(char));
这意味着 的值description
不为NULL。
您的printf
陈述依赖于if (description == NULL)
返回 true 的检查,但它description
仍然不是NULL
realloc
将返回 NULL,因此设置description
为NULL
如果分配内存失败。
推荐阅读
- java - 如何从 json 结果集中获取状态?
- javascript - 怎么改变大小
在浏览器中? - java - Hibernate Criteria - 如何将函数应用于 ORDER BY?
- sql - 如果我在 AG 中有异步副本怎么办?此查询仍显示异步副本的同步??SQL Server 有向无环图
- windows-10 - VirtualBox:主机无法通过 SSH 访问来宾
- c++ - 我们如何在 cpp 中使用带有虚函数的模板进行抽象?
- tensorflow - 如何将python版本的tensorflow代码翻译成java版本?
- r - 按 R data.table 中可变数量的列分组
- android - 所有设备都从 values-xxxhdpi 而不是 values 文件夹中获取资源
- wordpress - 使用 markerClusterGroup (Leaflet.js) 在 Wordpress 上创建地图