メモリリークの最も単純なケースは、オブジェクトを動的に作成してすぐに参照を失うことだと思います。この短い例では、作成した変数への参照がただちに失われ、メモリリークが発生します。プログラムが終了するとすぐに、オペレーティングシステムはプログラムが割り当てたメモリを再利用するため、メモリリークを認識するのが難しくなります。
プログラムが長時間実行されると問題が深刻になります。メモリリークが悪化し、コンピュータのパフォーマンスが著しく低下します。
例:この不自然と無用の例では、オブジェクト参照を保持する
#include <iostream>
// Object is being created, allocated on the heap then function immediately exits, losing any reference to the object. This is a memory leak
void createObject()
{
int* x = new int;
}
int prompt()
{
int response;
std::cout << "Run again?\n";
std::cin >> response;
return response;
}
int main()
{
while(continue)
{
createObject();
// Running the program again and again will exacerbate the memory leak.
continue = prompt();
}
return 0;
}
正しい方法:
int* createObject()
{
int* x = new int;
return x;
}
int main()
{
// Pointer to the object created in the function in this scope is created, so we still have access to the variable.
int* a = createObject();
return 0;
}
希望これは、あなたのクラスで幸運を助けます!
「*動作していないようです」と定義してください* – WhiZTiM
プロセスメモリを確認してください。ループ継続で増加します –
プログラムのメモリ使用量を見ると、メモリが使用できなくなっています。私はちょうど悪い割り当てエラーを取得します。 –