每次我将输入存储在 char* 中分配的空间之上时,我都会遇到 free() 错误。这是错误:
*** ./input' 错误:free():下一个尺寸无效(快速):0x09713008 ***
当我删除 free() 时,程序运行完美,即使我输入的大小超过了分配的大小。为什么会这样?我该如何预防?这是我的代码供引用:
int main(void){
float x; // used to store the float the user entered.
char c; // character used to check if the user entered a character after the float
int loop=0;
char * usr_input = malloc(50); //allocates memory to store the string from the stdin
// loops until the user enters a float and only a float
do{
//gets the input string from stdin
scanf("%s",usr_input);
if(usr_input==NULL)
printf("You've entered a large number that isnt supported. Please use at most 5 digits\n");
// parses the input received and checks if the user entered a float and only a float.
// breaks the loop if they did
else if(sscanf(usr_input,"%f %c",&x,&c) == 1){
if (x!=inf)
loop=1;
else
printf("Input was too large. Try again");
}
// tells the user they entered invalid input. Loop value doesnt change so function loops again
else{
printf("Invalid input. Try again\n");
}
}
while(loop==0); // condition for the loop
free(usr_input);//crashes here
return x; // returns the valid float that was entered
}
最佳答案
When I remove the free(), the program runs perfectly even though I'm entering more than the allocated size.
输入超过分配的大小称为未定义行为。这是一个错误,尽管您的程序可能看起来“运行良好”。
未定义行为的主要问题是您的程序不会快速失败。本质上,对未定义行为的惩罚会延迟到 future 的某个时间——例如,当您再次分配时,或者当您释放时。
malloc
在分配的 block 中存储一些特殊信息,让 free
运行。 “nvalid next size”错误通常意味着您的代码已经覆盖了一些隐藏的数据 block 。
要解决此问题,您需要更改代码,使其永远不会写入超过分配的长度。如果您无法准确检测需要更改的点,请考虑使用 valgrind或其他内存分析器。
要防止 scanf
覆盖您分配的大小,请使用格式字符串中的大小:
scanf("%49s",usr_input); // Pass 49 for the length, because you have 50 bytes, and you need 1 byte for '\0'
关于c - 为什么 free() 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22901208/