[英]Memory deallocation c++
我显然误用了delete
。 为什么这个程序会填满我的记忆?
void f(int* x){
x = new int[42];
}
int main(){
while(true){
int* x;
f(x);
delete[] x;
}
return 0;
}
如何从main
函数内部释放在f
分配的内存?
您实际上并没有在外部函数中修改x
变量。
为此,您必须依靠f
的返回值:
int* f(){
return new int[42];
}
int main(){
while(true){
int* x = f();
delete[] x;
}
return 0;
}
或通过引用传递变量x
:
void f(int*& x){
x = new int[42];
}
int main(){
while(true){
int* x;
f(x);
delete[] x;
}
return 0;
}
或者使用指向指针的指针作为f
的参数:
void f(int** x){
*x = new int[42];
}
int main(){
while(true){
int* x;
f(&x);
delete[] x;
}
return 0;
}
等等...
函数中存在内存泄漏
void f(int* x){
x = new int[42];
}
您分配内存,但永远不会释放它。 函数参数是函数的局部变量。 该函数处理原始指针的副本。 复制的任何更改都不会影响原始参数。
并且mpreover程序具有未定义的行为,因为指针x
未初始化。
int main(){
while(true){
int* x;
^^^^^^
f(x);
delete[] x;
}
return 0;
}
您需要通过引用传递原始指针。 所以功能应该像
void f(int* &x){
x = new int[42];
}
叫像
f(x);
或定义为
void f(int* *x){
*x = new int[42];
}
叫像
f( &x );
通过引用传递参数。 您正在通过价值传递它。
因此,您可能要考虑构建使用RAII的函子/类/结构。
我的意思是说标准库如何处理大量分配。
struct A {
A(){/*allocate mem*/}
~A(){/*deallocate mem*/}
}
对于您的特定功能,
void f(int** x);
是您想要的签名。 这将允许您通过指向数组的指针来修改数组。 虽然...我仍然建议不要这样做...原因是如果您决定分配一堆数组呢? 主要方法是否负责分配内存?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.