【问题标题】:free() the reserved data with mallocfree() 使用 malloc 保留的数据
【发布时间】:2018-05-23 06:40:14
【问题描述】:


我已经编写了这个程序,它创建了一个用户给出的书籍列表,我无法在程序结束时释放 my_value 并得到很多错误。
这是我的代码

#include <stdio.h>
#include <stdlib.h>


int main(){



int n;
printf("Please Enter the Number of Books:\n");
scanf("%d",&n);
char **array=(char *) malloc((n+1)*sizeof(char *));

for(int i=0;i<n;i++){
 array[i] = (char *)malloc(sizeof(char *));
}

for(int i=0;i<n;i++){
char *my_value=(char *) malloc(sizeof(char)*100);
printf("Please Enter the Name of the %dth Book:\n",i+1);
scanf("%s",my_value);
*(array+i)=my_value;
free(my_value);

}

for(int i=0;i<n;i++){
 printf("\n The Book Nr.%d is %s \n",i+1,*(array+i));
}
for(int i=0;i<n;i++){
 free(array[i]);
}
free(array);


return 0 ;
}

【问题讨论】:

  • 您遇到了什么样的错误?你在哪个平台上开发?你用过Valgrind吗?您应该显示一些示例数据并报告您从该示例数据中得到的错误。也许只有两本书的数据;这可能就足够了。请阅读有关如何创建 MCVE (minimal reproducible example) 的信息,注意数据和输出(实际与预期)都是 MCVE 的一部分。
  • 你不需要转换malloc的结果。见Do I cast the result of malloc?。此外,char **array=(char *) malloc((n+1)*sizeof(char *)) 具有不兼容的指针类型。

标签: c malloc c99


【解决方案1】:

首先,在

char **array=(char *) malloc((n+1)*sizeof(char *));

您不需要n+1 指针,因为您只使用n

然后,这个循环

for(int i=0;i<n;i++){
   array[i] = (char *)malloc(sizeof(char *));
}

是不必要的(也是错误的)。 array[i] 将在之后被覆盖。

在下一个循环中

*(array+i)=my_value; // is array[i] = my_value
free(my_value);      // <=== why? remove that line!

你释放了你刚刚分配的东西——array[i] 从那时起就不能再使用了!导致未定义的行为。

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 2011-12-15
    • 2014-05-05
    • 2015-05-28
    • 1970-01-01
    • 2014-05-21
    • 2011-12-19
    • 1970-01-01
    • 2012-06-10
    相关资源
    最近更新 更多