[英]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.