从函数返回的堆分配
The function has a problem:
void myAllo(int mySize, char *myChar )
{
myChar = new char[mySize];
}
堆分配会从 myAllo()
返回吗? 我不这么认为,因为 myChar
指向的内存会 当 myAllo
返回时被释放。
正确的 ?
欢迎任何评论。
谢谢
The function has a problem:
void myAllo(int mySize, char *myChar )
{
myChar = new char[mySize];
}
Will the heap allocation be returned from myAllo()
?
I do not think so, because memory pointed by myChar
will
be deallocated when myAllo
returns.
Right ?
Any comments are welcome.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不会。参数
myChar
是按值传递给myAllo()
的,因此您只需修改指针的本地副本,而不是修改指针中的指针值。调用者的上下文。又不行了。函数退出时会泄漏分配的内存。要取消分配内存,您需要对
new[]
返回的指针调用delete[]
,但当函数退出时,该指针将超出范围。有多种方法可以解决您的问题。
让调用者传入指向已分配内存的指针地址,现在您可以修改调用者指针指向的内容。
类似地,您的函数可以接受对指针的可变引用
返回指向已分配内存的指针
比上述所有解决方案更好,不是返回原始指针,而是返回智能指针
No. The argument
myChar
is being passed by value tomyAllo()
, so you're simply modifying a local copy of the pointer, not the value of the pointer in the caller's context.No again. The function leaks the allocated memory when it exits. To de-allocate memory you need to call
delete[]
on the pointer returned bynew[]
but this pointer goes out of scope when the function exits.There are several ways to fix your problem.
Have the caller pass in the address of the pointer which will point to the allocated memory, now you can modify what the caller's pointer points to.
Similarly, your function could accept a mutable reference to the pointer
Return a pointer to the allocated memory
Better than all of the above solutions, instead of returning raw pointers, return a smart pointer
不。
不,这是内存泄漏。
No.
No, this is a memory leak.
为了获得分配的内存,您需要将函数编写为
并调用它
,或者编写为
并调用它
In order to get the memory you allocated you need to write the function as
and call it
or as
and call it
动态内存(新)仅在您显式释放时才会释放。
myChar 超出范围并被自动清理,但指针的“清理”不会释放它指向的任何内存。这允许我有多个指针指向相同的数据。
或者更好的是,使用向量:
Dynamic memory (new) is only released when you explicitly release it.
myChar goes out of scope and is automatically cleaned up, but a pointer's "clean up" does not deallocate any memory it points at. This allows me to have multiple pointers point at the same data.
Or better yet, use a vector: