当我发现有关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[]
。因此,它的大小始终是指针的大小,而不是数组的大小。
您应该跟踪自己分配的块大小。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句