Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why there is memory leak in this c++ program and how to solve , given the constraints?

This is Minimal Working Example, for the problem I am facingin in my real code.

#include <iostream>

namespace Test1 {
static const std::string MSG1="Something really big message";
}

struct Person{
  std::string name;
};

int main() {
    auto p = (Person*)malloc(sizeof(Person));
    p = new(p)Person();
    p->name=Test1::MSG1;

    std::cout << "name: "<< p->name << std::endl;
    
    free(p);
    
    std::cout << "done" << std::endl;

    return 0;
}

When I compile it and run it via valgrind it gives me error: definitely lost: 31 bytes in 1 blocks


Constraints

  1. I am bind to use malloc in the example above, as in my real code I use a C library in my C++ project, which uses this malloc internally. So can’t get away from malloc usage, as I don’t do it explicitly anywhere in my code.
  2. I need to reassign std::string name of Person again and again in my code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You must manually call the destructor before free(p);:

p->~Person();

Or std::destroy_at(p), which is the same thing.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading