c - 为什么 free() 不起作用?

标签 c malloc free core abort

每次我将输入存储在 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/

相关文章:

c - 如何检查内存是否可用于读/写操作?

C:删除链表

c - 编写一个 C 程序,根据给定的整数数组创建新数组,将所有偶数移到所有奇数之前

c - #包括文件

c - 返回一个用 malloc 分配的数组而不使用 return

c++ - 带有初始化器的堆上的多维数组

C - 指针的正确语法

c - Valgrind 缩进(和低于主要)

c - 需要关于在 C 中实现 malloc 和 free 的建议

c - 当目标值等于程序中的 res 值时,如何终止程序?