当我发现 malloc
时,我一直在尝试在 C 编程中更加“内存感知”。方法和类似的内存管理方法。但是,当我尝试使用 realloc
时为 char*
分配尽可能少的内存在我的程序中的实例中,我发现它并没有像我想象的那样保存那么多数据。
这是我的代码:
int foo(char * arg){
if(condition){
//code here
}else if(other_condition){
char * cmd = malloc(5);
fgets(cmd,sizeof(cmd),stdin);
//more code here
if(another_condition){
//more code
cmd = realloc(cmd,new_size) //once in this if block, but also once in another block
fgets(cmd,sizeof(cmd),stdin);
//more code
}
//more else-if blocks here
free(cmd)
}
//more else-if blocks here
}
具体来说,在上面的代码片段中,new_size
是 255,尽管在其他地方已设置为其他尺寸。问题是,当我运行该程序时,我只得到 7 个输入字母。
示例输出:
...
Enter filename: document1
Loading file "documen"
Load failed
...
(here the next time fgets is called it fails because "t1" is not valid input for the program)
据我了解,它正在接收 "t1"
因为我没有清除输入缓冲区,但我想解决的是我只接收输入的前 7 个字符。如果我打电话sizeof(cmd)
中间,它告诉我 cmd
占用的内存是 8。我还尝试使用 char * cmd = malloc(5 * sizeof(char))
分配内存和cmd = realloc(cmd,255 * sizeof(char))
但这并没有解决问题。我可能应该提到,如果我使用 char cmd[255]
声明变量语法,我不调用 malloc
, realloc
,或free
任何地方都不再出现此问题。
最佳答案
fgets(cmd,sizeof(cmd),stdin);
这里cmd
是一个char*
而不是char[]
。因此,它的大小始终是指针的大小,而不是数组的大小。
您应该跟踪自己分配的 block 大小。
关于c - malloc 和 free : pointer being freed was not allocated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26173339/