当我发现了有关malloc
方法和类似的内存管理方法时,我一直试图在C编程中使用“内存感知”。但是,当我尝试使用realloc
为我的程序中的char*
实例分配尽可能少的内存时,我发现它并没有像我想象的那样保存尽可能多的数据。malloc和free:被释放的指针没有被分配
这里是我的代码:
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
,则不会再出现此问题。
如果您在支持[GNU'getline()'](https://www.gnu.org/software/libc/manual/html_node/Line-Input.html)的平台上,您可能需要考虑使用它 - 它有助于管理输入行的缓冲区的动态分配(尽管您仍然需要一个变量来跟踪大小)。 – 2014-10-03 05:11:01
http://stackoverflow.com/questions/2478240/how-i-return-the-size-of-the-pointer-that-i-have-allocate-with-malloc – 2014-10-03 05:11:30