我试图从用户那里获取一系列字母,并将输入放入动态数组中。
然而,由于我不太明白的原因 - 如果用户输入超过 10 个字母,则 realloc 失败(返回 NULL 并打印“分配内存时出错!”)。我确实尝试将 realloc 更改为 calloc ,这似乎解决了问题,但我不确定为什么。
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char **argv) {
char *first_string, *second_string, *memory_check;
char user_input;
int first_string_size = 0, second_string_size = 0, debug =1;
first_string = malloc(sizeof(char));
second_string = malloc(sizeof(char));
// gets the strings from the user
printf("Input the first string:");
for(int i = 0;;i++) {
user_input= getchar();
if(user_input == EOF || user_input == '\0' || user_input == '\n') {
break;
}
first_string[i] = user_input;
memory_check = realloc(first_string, (i+1)*(sizeof(char)));
if(memory_check == NULL) {
printf("\nError allocating memory!\n");
break;
}
first_string_size = i;
if(debug == 1) {
printf("\n number of letters is %d", first_string_size +1);
printf("\n array size in memory is %d", sizeof(first_string) * (i+1));
}
}
return 0;
}
当然失败了:
memory_check = realloc(first_string, (i+1)*(sizeof(char)));
if(memory_check == NULL) {
printf("\nError allocating memory!\n");
break;
}
你正在使用memory_check
作为检查是否可以重新分配的标志,但不仅如此。
You have将其分配回first_string
.
在你的情况下,这是一个致命的赠品:前 10 次(当然,在你的情况下,这没有指定或定义,它是纯随机的),内存区域不需要移动,这说明它可以工作。但过了一段时间后,realloc
无法重用同一块(因为它太小)并且它会更改内存位置。
由于您没有更新它,因此您会得到未定义的行为。
你可以这样做:
memory_check = realloc(first_string, (i+1)*(sizeof(char)));
if(memory_check == NULL) {
printf("\nError allocating memory!\n");
free(first_string);
break;
}
first_string = memory_check;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)