原帖由 iwinux 于 2006-8-2 10:06 发表
因为刚刚学 C 语言,经常做练习的时候都需要用到getchar()之类的函数,为了方便,我参考《C语言的科学和艺术》这本书的代码,实现了一个getLine函数,这里我把代码贴出来,大家帮忙看看有什么bug,谢谢!
if (*line) {
free(*line);
}
[c ...
原帖由 flw10000 于 2006-8-2 11:18 发表
明白你的意思了
如果调用时已经malloc了,要先free,重新malloc,因为没法知道调用者malloc了多大空间!
原帖由 Bayweb 于 2006-8-2 13:00 发表
>>
>>
>>一般malloc之前都会检查一下是否为空,或者size是否为零。如果不是十分必要,
>>在函数的结尾务必free一下。
>>
>>
Since you always want each block of dynamically-allocated memory to be contiguous (so that you can treat it as if it were an array), you and realloc have to worry about the case where realloc can't make the old block of memory bigger ``in place,'' but rather has to relocate it elsewhere in order to find enough contiguous space for the new requested size. realloc does this by returning a new pointer. If realloc was able to make the old block of memory bigger, it returns the same pointer. If realloc has to go elsewhere to get enough contiguous memory, it returns a pointer to the new memory, after copying your old data there. (In this case, after it makes the copy, it frees the old block.) Finally, if realloc can't find enough memory to satisfy the new request at all, it returns a null pointer. Therefore, you usually don't want to overwrite your old pointer with realloc's return value until you've tested it to make sure it's not a null pointer. You might use code like this:
欢迎光临 Chinaunix (http://bbs.chinaunix.net/) | Powered by Discuz! X3.2 |