c - 使用 realloc 调整(减小)char 数组的大小并检查是否成功
问题描述
我尝试初始化一个动态char
数组,如果用户输入的字符串较小,该数组会减小。
问题是:我不知道,如果程序真的这样做了?我没有收到错误消息和正确的输出,但未使用的内存真的释放了吗?
char *input=(char*)malloc(100);
gets(input);
int a = strlen(input);
input = realloc(input, a+1);
解决方案
不要*alloc()
在 C 中转换结果。它不需要,只会给代码增加混乱,在最坏的情况下会掩盖错误,比如忘记#inlude <stdlib.h>
for *alloc()
。
线
input = realloc(input, a+1);
是有问题的,因为如果realloc()
失败并返回,您将丢失先前的指针值NULL
。更好的:
char *new_input = realloc(input, a+1);
if(!new_input) {
free(input);
// print some error message
return EXIT_FAILURE;
}
// everything fine:
input = new_input;
// use input
free(input);
PS:另外,正如其他人在评论中指出的那样:gets()
从您的词汇表中删除。假装它从未存在过。改为使用fgets()
。
推荐阅读
- python - Peewee:如何使用一组元组进行查询?
- android - 无法使用 var 在 Kotlin 中设置对象的属性
- java - Netbeans 11.3 和 Java 14 预览功能
- python - 如何清空 Gtk.Window 然后添加新的小部件?
- android - 如何修复 Android Studio 中的 INSTALL_FAILED_INVALID_APK 错误?
- java - Amazon EMR 集群停留在启动状态
- google-cloud-firestore - firestore 安全规则获取动态密钥的值?
- azure - Azure 应用服务显示 6 个数据输入指标实例并显示 5 个 CPU 时间指标实例
- c# - 识别在 DiagramControl 对象上选择的控件类型
- node.js - 为什么 Rollup 插件通过本地文件正确加载但不使用 NPM 库?