Anf*_*nee 2 c malloc free core abort
每当我将输入存储在char*中的已分配空间之上时,我就会收到free()错误.继承人错误:
*** Error in ./input': free(): invalid next size (fast): 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
}
Run Code Online (Sandbox Code Playgroud)
当我删除free()时,程序运行完美,即使我输入的分配大小超过了分配的大小.
输入超过分配的大小称为未定义行为.这是一个错误,尽管您的程序可能看起来"运行正常".
未定义行为的主要问题是您的程序不会快速失败.从本质上讲,对未定义行为的惩罚会延迟到将来的某个时间 - 例如,当您再次分配或者释放时.
malloc将一些特殊信息存储在允许free运行的已分配块中."nvalid next size"错误通常意味着您的代码已经写入了一些隐藏的数据块.
要解决此问题,您需要更改代码,使其永远不会写入已分配的长度.如果您无法准确检测需要更改的斑点,请考虑使用valgrind或其他内存分析器.
要防止scanf写入已分配的大小,请使用格式字符串中的大小:
scanf("%49s",usr_input); // Pass 49 for the length, because you have 50 bytes, and you need 1 byte for '\0'
Run Code Online (Sandbox Code Playgroud)