首页 > 解决方案 > 使用 realloc 调整(减小)char 数组的大小并检查是否成功

问题描述

我尝试初始化一个动态char数组,如果用户输入的字符串较小,该数组会减小。

问题是:我不知道,如果程序真的这样做了?我没有收到错误消息和正确的输出,但未使用的内存真的释放了吗?

char *input=(char*)malloc(100);
gets(input);
int a = strlen(input);
input = realloc(input, a+1);

标签: crealloc

解决方案


不要*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()


推荐阅读