【发布时间】:2015-03-09 08:29:46
【问题描述】:
我正在尝试为输入文件编写缓冲区。缓冲区应始终包含定义数量的数据。如果使用了几个字节的数据,缓冲区应该从文件中读取数据,直到它再次具有定义的大小。
const int bufsize = 10;
int *field = malloc(bufsize*sizeof(int)); //allocate the amount of memory the buffer should contain
for(i=0;i<bufsize;++i) //initialize memory with something
*(field+i) = i*2;
field += 4; //Move pointer 4 units because the first 4 units were used and are no longer needed
field= realloc(field,bufsize*sizeof(int)); //resize the now smaller buffer to its original size
//...some more code were the new memory (field[6]-field[9]) are filled again...
这是我目前尝试如何做的一个简短示例(没有文件,因为这是不工作的部分),但 realloc() 总是返回 NULL。在这个例子中,使用了前 4 个单元,所以指针应该向前移动,并且应该分配内存末尾的缺失数据(这样它将再次包含 10 个元素)。我做错了什么?
如果有人可以帮助我,我将非常感激
【问题讨论】:
-
field += 4; //Move pointer 4 units because the first 4 units were used and are no longer needed然后你怎么去free呢? “但 realloc() 总是返回 NULL”,这就是为什么你应该使用一个临时变量来freefield以防realloc失败。 -
您正在调用未定义的行为。您传递给
realloc的地址不是从malloc、calloc或realloc返回的地址。您不能传递恰好在动态分配的缓冲区范围内某处的 any 地址。它必须是 非 NULL 地址直接从这些函数之一返回而无需修改。