How to fix this memory leak in C++ project? -


i have simple code snippet:

struct simple_string {     simple_string(size_t size, char ch)     : buffer_(new buffer(std::basic_string<char, std::char_traits<char>>(size, ch).c_str(), size)) //first memory leak     {     }      ~simple_string()     {         buffer_->release();         delete buffer_;     }      struct buffer     {         explicit buffer(const char* str, size_t size)         : str_(new char[size + 1]), //second memory leak         count_(1)         {             std::char_traits<char>::copy(str_, str, size + 1);         }          void release()         {             if (this != nullptr)             {                 --count_;                  if (count_ == 0)                 {                     delete[] str_;                 }             }         }          void acquire()         {             ++count_;         }          char* str_;         size_t count_;     } *buffer_; };  int main() {     simple_string a(3, 'a');      return 0; } 

i don't understand, why memory leaks exist. both raw pointers deleted in end of program life. maybe should not have create pointers in initializer lists of constructors?

i don't memory leak using g++ 4.8.2 + valgrind 3.10.

i in vs 2015 ee detecting crtdbg_map_alloc false positive.

set str_ , buffer_ nullptr after deleting pointers , call destructor explicitly: a.~simple_string();, call destructor twice nothing doing second time show no memory leak because first time destructor called before outputting memory leaks results.

edit: false positive memory leak can work arounded (in vs2015 ee @ least) creating simple_string object in function instead of in main():

void foo() {     simple_string a(3, 'a'); }  int main()  {     foo();      return 0; } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -