2016-10-14 16 views
0

ここでは単純化したコードを示しますが、問題に関係しないものはすべて削除しました。valgrindによってメモリリークが検出されましたが、空きがないことを忘れた行が見つかりません

#include <iostream> 
#define N 3 

int main() { 

    int *input; 
    int **cl; 

    input = new int[N]; 
    cl = new int*[N]; 
    for(int i = 0; i < N; i++) { 
     cl[i] = new int[N]; 
    } 


    for(int i = 0; i < N; i++) { 
     delete[] cl[i]; 
    } 
    delete[] cl; 
    delete[] input; 

    return 0; 
} 

そして、valgrindの出力:

==5782== HEAP SUMMARY: 
==5782==  in use at exit: 72,704 bytes in 1 blocks 
==5782== total heap usage: 6 allocs, 5 frees, 72,776 bytes allocated 
==5782== 
==5782== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1 
==5782== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) 
==5782== by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21) 
==5782== by 0x40104E9: call_init.part.0 (dl-init.c:72) 
==5782== by 0x40105FA: call_init (dl-init.c:30) 
==5782== by 0x40105FA: _dl_init (dl-init.c:120) 
==5782== by 0x4000CF9: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so) 
==5782== 
==5782== LEAK SUMMARY: 
==5782== definitely lost: 0 bytes in 0 blocks 
==5782== indirectly lost: 0 bytes in 0 blocks 
==5782==  possibly lost: 0 bytes in 0 blocks 
==5782== still reachable: 72,704 bytes in 1 blocks 
==5782==   suppressed: 0 bytes in 0 blocks 
==5782== 
==5782== For counts of detected and suppressed errors, rerun with: -v 
==5782== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) 

私は多分私が見ることができないいくつかの愚かなエラーがある、C++を学び始めました。

割り当て時に「メモリ不足」というエラーがない場合はチェックしてくださいが、無視するとコードがより明確になります。私はまた、私が使用できることを知っている。ベクタと割り振りは気にしませんが、私はまだ私が間違っていることを心配しています。

+12

最終的には 'C++ 'を学び、これに対処する必要はありません。 – drescherjm

+7

正しいと思われますが、これができればマニュアルメモリ管理が避けられる理由です。 – NathanOliver

+1

@sashoalm新しいものを削除し、typcallyだけmallocをラップし、無料です。 – NathanOliver

答えて

1

C++には、メモリ管理をカプセル化するツールが用意されています。

#include <iostream> 
#include <vector> 

int main() { 
    // read the size for the vectors 
    int n; 
    std::cin >> n >> '\n'; 

    // allocate vector with n elements 
    auto input = std::vector<int>{n}; 

    // read the elements 
    for(int i = 0; i < n; i++) { 
     std::cin >> std::setw(1) >> input[i]; 
    } 
    // print them 
    for(const auto& d : input) { 
     std::cout << d << std::endl; 
    } 

    // allocate the vectors and store 1 in each field. 
    auto Cl = std::vector<std::vector<int>>{n, std::vector<int>{n, 1}}; 
    auto Cr = std::vector<std::vector<int>>{n, std::vector<int>{n, 1}}; 

    return 0; 

    // will safely release all the memory here. 
} 

これはC++によく似ていて、Cには似ていません。ベクトルは自動的にすべてのメモリ管理を自動的に処理します。

注意:私はこのコードをテストしていないので、おそらくいくつかのバグが含まれています。私はC++ 11の構文を前提としていますが、コードを古いC++構文にも変更するのは簡単です。

0

今、あなたはそれが明確にここに答えを持っていたものと同じ問題ですvalgrindの出力を追加したこと:Valgrind: Memory still reachable with trivial program using <iostream>

短編小説は、それがそのレポートを引き起こし、あなたのコードではないということです。あなたはmain()からすべてを削除して返すだけで、valgrindはあなたにその漏れを与えます。

説明のためにその質問に関する受け入れられた答えをお読みください。

関連する問題