realloc在尝试分配新内存之前是否进行解除分配?

huangapple go评论90阅读模式
英文:

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

来自reallocman页面:

对于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.

https://en.cppreference.com/w/c/memory/realloc

答案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.

huangapple
  • 本文由 发表于 2020年1月7日 01:34:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616524.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定