重新分配返回 null?
我用 malloc 分配了一些内存 - 大约 128 字节。
后来,我用大约 200 字节调用 realloc,但它返回 null!
如果我释放它,它会返回一个有效的指针,然后返回另一个malloc,但是我想使用realloc。
什么可以解释这种行为(我显然没有耗尽内存)?这是有效的行为吗?
代码位:
//class constructor
size = 0;
sizeAllocated = DEFAULT_BUFFER_SIZE; //64
data = (char*)malloc(sizeAllocated * sizeof(char)); //data is valid ptr now, I've checked it
data[0] = '\0';
//later on:
//append function
bool append(char** data, const char* str, size_t strLen) {
if((size + strLen) >= sizeAllocated) {
sizeAllocated += strLen + 1 + BUFFER_ALLOCATION_STEP;
char* temp = realloc(*data, sizeAllocated * sizeof(char));
if(temp)
*data = temp;
return( temp != NULL );
}
编辑:已修复。我超载了<<我的类的运算符,并让它返回 *this 而不是 void。不知怎的,这把一切都搞砸了!如果有人能解释为什么会发生这种情况,那就太好了!
I allocate some memory with malloc - about 128 bytes.
Later on, I call realloc with about 200 bytes, but it's returning null!
It returns a valid pointer if I do free, and then another malloc, however I would like to use realloc.
What could explain this behavior (I clearly am not running out of memory)? Is this valid behavior?
Code bits:
//class constructor
size = 0;
sizeAllocated = DEFAULT_BUFFER_SIZE; //64
data = (char*)malloc(sizeAllocated * sizeof(char)); //data is valid ptr now, I've checked it
data[0] = '\0';
//later on:
//append function
bool append(char** data, const char* str, size_t strLen) {
if((size + strLen) >= sizeAllocated) {
sizeAllocated += strLen + 1 + BUFFER_ALLOCATION_STEP;
char* temp = realloc(*data, sizeAllocated * sizeof(char));
if(temp)
*data = temp;
return( temp != NULL );
}
EDIT: fixed. I was overloading the << operator for my class, and had it return *this instead of void. Somehow this was screwing everything up! If anyone could explain why this happen, it would be nice!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于以下评论已添加到问题中
现在我们可以弄清楚发生了什么。您用一个不具有相同值的常量替换了 sizeAllocation。出于调试目的,添加一条将输出 sizeAllocation 值的语句,您会感到惊讶。
Since the following comment was added to the question
Now we can figure out what happened. You replaced sizeAllocated with a constant that DID NOT have the same value. For debugging purposes, add a statement that will output the value of sizeAllocated and you will be surprised.