割り当ては、ライブラリコードとループ内で実行されるコードの割り当て解除と常にペアにする必要があります。
基本的に、未参照の未参照メモリが累積されず、それによってプロセスのメモリ消費が増加しないようにします。
単純に終了したいときに割り当て解除をスキップすることは許容されますが(一般的には嫌なことですが)、割り当てをたくさんやることがあれば少し早くすることができます。 C++で
、割り当ておよび割り当て解除はデストラクタ(RAII)を介して、暗黙的に対にすることができる。実際に
#include <utility>
#include <memory>
#include <stdio.h>
#include <stdlib.h>
struct Free{
void operator() (void* x){
free(x);
}
};
int main(){
char *p = new char;
delete p; //an explicit deallocation
std::unique_ptr<char, Free> ptr { (char*)calloc(1,100) };
return 0;
//an implicit deallocation
//-- you don't see the free but unique_ptr's destructor does call it here
}
を、デストラクタに依存するC++でダイナミックメモリを扱う絶対好ましい方法です。
valgrindなどのツールを使用して、プログラムの実行中に割り振りと割り当て解除がペアになっていることを確認できます(g ++標準ライブラリは最初に直接的または間接的にnewを呼び出したときに、私は経由して上記のプログラムを実行するとfree
秒)
と一致する必要があります。
valgrind ./a.out
私が取得:
==25629== Memcheck, a memory error detector
==25629== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==25629== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==25629== Command: ./a.out
==25629==
==25629==
==25629== HEAP SUMMARY:
==25629== in use at exit: 72,704 bytes in 1 blocks
==25629== total heap usage: 3 allocs, 2 frees, 72,805 bytes allocated
==25629==
==25629== LEAK SUMMARY:
==25629== definitely lost: 0 bytes in 0 blocks
==25629== indirectly lost: 0 bytes in 0 blocks
==25629== possibly lost: 0 bytes in 0 blocks
==25629== still reachable: 72,704 bytes in 1 blocks
==25629== suppressed: 0 bytes in 0 blocks
==25629== Rerun with --leak-check=full to see details of leaked memory
==25629==
==25629== For counts of detected and suppressed errors, rerun with: -v
==25629== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
これは、標準ライブラリ(72,704バイトのもの)による割り当てだけが割り当て解除と対になっていないため、すべてが正常であることを意味します。
私には壊れた/怠惰な音。 –
メモリを割り当てたら、解放する必要があります。例外なく。それ以外の場合はメモリリークを取得します。 – ForceBru
**ヒープ再利用性**を向上させるには、 'free()'を使うのは良い考えです。それ以外の場合、大規模なソフトウェアの場合は、**ヒープ**または**フリーストア(C++レキシコン内)**が使い果たされ、残りは災害になります。 –