2014-08-29 72 views
1

我遇到了一個問題,當我有一個std ::向量在一個結構中,我堆分配該結構,當結構變得free'd,向量泄漏。有關如何防止這種情況的任何想法?內存泄漏與分配的結構包含一個向量

下面的代碼:

#include <cstdlib> 
#include <string> 
#include <vector> 

struct foo { 
    std::vector<std::string> bar; 
}; 

const std::vector<std::string> kSample = {"test", "1", "2", "3", "4", "5"}; 

int main(int argc, char *argv[]) { 
    struct foo *allocated = new foo; 
    for (const auto& i : kSample) { 
    allocated->bar.push_back(i); 
    } 
    free(allocated); 
    return 0; 
} 

這裏從運行此代碼是在Valgrind的結果:

==18131== 192 bytes in 1 blocks are definitely lost in loss record 51 of 76 
==18131== at 0x6DFB: malloc (in /usr/local/Cellar/valgrind/3.9.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so) 
==18131== by 0x4728D: operator new(unsigned long) (in /usr/lib/libc++.1.dylib) 
==18131== by 0x10000283D: std::__1::__split_buffer<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >&>::__split_buffer(unsigned long, unsigned long, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >&) (in ./build/tools/test) 
==18131== by 0x100001EEC: std::__1::__split_buffer<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >&>::__split_buffer(unsigned long, unsigned long, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >&) (in ./build/tools/test) 
==18131== by 0x100001D9B: void std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > >::__push_back_slow_path<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) (in ./build/tools/test) 
==18131== by 0x100001278: main (in ./build/tools/test) 
==18131== 
==18131== LEAK SUMMARY: 
==18131== definitely lost: 192 bytes in 1 blocks 
==18131== indirectly lost: 0 bytes in 0 blocks 
==18131==  possibly lost: 0 bytes in 0 blocks 
==18131== still reachable: 0 bytes in 0 blocks 
==18131==   suppressed: 25,768 bytes in 377 blocks 
+3

'new'和'free'是兩個完全不同的內存分配系統。不要合併它們。所有'new' /'new []'需要相應的'delete' /'delete []'。 – 0x499602D2 2014-08-29 03:52:53

+0

'main'可能真的只是'foo分配{{std :: begin(kSample),std :: end(kSample)}};'。 – chris 2014-08-29 03:54:11

+0

另外,你爲什麼用'new'創建結構? C++不是Java - 你不需要使用'new'來創建對象。另外,爲什麼在聲明中使用'struct'關鍵字?你在閱讀'C'書籍而不是'C++'書籍嗎? 'foo分配;'這就是你需要的。 – PaulMcKenzie 2014-08-29 03:54:49

回答

5

你應該叫delete allocated;newdelete應成對使用。