为什么free(usr_input)不起作用?

时间:2014-10-14 06:05:00

标签: c malloc free core abort

每次我将输入存储在free()的分配空间之上时,我都会收到char*错误。这是错误:

 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
}

1 个答案:

答案 0 :(得分:2)

你正在破坏堆 - 其他一切都只是未定义的行为。变化:

scanf("%s",usr_input);

为:

scanf("%49s",usr_input);

然后你将无法溢出输入缓冲区。

<小时/> 另请注意,这没有任何意义:

if(usr_input==NULL)
    printf("You've entered a large number that isnt supported. Please use at most 5 digits\n");

你应该把它改成这样的东西:

if (strlen(usr_input) > 5)
    printf("You've entered a large number that isnt supported. Please use at most 5 digits\n");