英文:
Does realloc deallocate before trying to allocate new memory?
问题
我在这里遇到了一些问题 - 我想更多地了解realloc函数 -
如果我们将指针发送给realloc,并且它无法分配内存[返回null],之前分配的内存是否被释放?尽管我们失败了?
ePointer = (Element*)realloc(stack->content, (sizeof(Element) * capacityOfStack(stack) * 2));
当stack->content
作为指针时,如果我们现在失败并且ePointer
变成了NULL
,那么stack->content
就不再分配内存了吗?
非常感谢!
英文:
I'm having trouble with my exercise here - I want to know about the realloc function a bit more -
If we send a pointer to the realloc, and it fails to allocate memory [returns null] does the memory that used to be allocated, now deallocated? although we failed?
ePointer = (Element*)realloc(stack->content, (sizeof(Element) * capacityOfStack(stack) * 2));
when stack->content
being the pointer ofcourse, if we failed now have ePointer
as NULL
, then stack->content
is no longer allocated?
Thanks alot!!
答案1
得分: 3
来自realloc
的man
页面:
对于realloc(),如果重新分配失败,输入指针仍然有效。
英文:
From the man
page for realloc
:
For realloc(), the input pointer is still valid if reallocation failed.
答案2
得分: 2
stack->content
仍然有效。如果realloc
失败,它会返回NULL,但旧的内存块仍然有效,这就是接口。
英文:
stack->content
is still valid. If realloc
fails, it returns NULL, but the old block of memory remains valid, that's the interface.
答案3
得分: 1
从man 3 realloc
中:
如果
realloc()
失败,原始块保持不变;它不会被释放或移动。
英文:
From man 3 realloc
> If realloc()
fails, the original block is left untouched; it is not freed or moved.
答案4
得分: 0
realloc()
在尝试重新分配之前不会释放内存。它首先尝试分配一个新的内存块。如果分配失败,它会返回,旧指针仍然有效。如果成功,然后将原始块的内容复制到新块中,然后调用free()
释放原始块。
英文:
realloc()
does not de-allocate before trying to allocate again. What it does is first try to allocate a new block. If it fails, it returns and the old pointer is still valid. If it succeeds, then it copies the content from the original block into the new block, and then calls free()
on the original block.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论