Mohamad-Jaafar NEHME
Mohamad-Jaafar NEHME

Reputation: 1215

How to free an assigned static value in C++?

Valgrind reports that my code (showed below) is causing a memory leak.

view *vi = new view(IPs);
initialView = *vi;
//delete vi;

So, I added delete. But deleting vi makes initialView empty!! And causes several problems to valgrind. What shall I do?

By the way, This is the equal operator of class view!

view & operator = (const view& v){
        vp = std::vector <process>(v.vp);
    return *this;
}

Upvotes: 0

Views: 109

Answers (3)

Raghav S.Vaidyanathan
Raghav S.Vaidyanathan

Reputation: 36

A pointer is assigned a memory location from the heap or free store when you use the new command. The thing is, after using this memory location through the pointer, the programmer has to explicitly de-allocate that memory block using the delete command. Otherwise, the program will run out of dynamic memory and crash. Basically, that's what a memory leak leads to.

When the delete pointer is used, it simply resets the value of pointer to null and makes the memory block free for re usage. All you have to do is delete the pointer you use AFTER its designated use. for example:

for(int i=0;i<1000;i++)
    {
    int* ptr=new int;
    *ptr=i;
    cout<<*ptr;  // ptr has been used, don't need it anymore
    delete ptr; //if you don't use this, memory leak will occur
    }

Upvotes: 2

Daerst
Daerst

Reputation: 973

From your code, it's hard to tell. Which static variables are you referring to in the title?

For valgrind to be happy, you of course have to delete vi. In your code, I can't see any dependencies between initialView and vi after the assignment - the vector constructor creates a copy of v's process list, and if those processes are not deleted with vi, this should be fine. If there are other dependencies causing you problems, try to eliminate them.

Upvotes: 1

ravi
ravi

Reputation: 10733

You can replace this raw pointer with shared_ptr if possible. It's based on reference counting and hence can take care of freeing the memory when no one is pointing to it.

Upvotes: 1

Related Questions