954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Double freeing of freed memory

Hi, I am newbie in C++. In a C++ Program, i am getting error message as "Double freeing of freed memory may be in class 'WSO'. copy constructor and operator= is not defined." I haven't defined any copy-constructor and operator overloading in Class 'WSO' (since i haven't use any assignment or copying object sort of things). Private member function of Class CNN uses a object pointer of another class 'NSA'. I used copy-constructor for this calss 'NSA'.

So my question is what could be the possibility of double freeing the memory.

destructor of Class 'WSO' just deletes pointer member of class 'NSA'.

majesticmanish
Newbie Poster
14 posts since Dec 2008
Reputation Points: 10
Solved Threads: 0
 

I believe your compiler is warning you because you are using heap-allocated (new'ed) data in your class and haven't defined operator= .
It could be that it isn't even heap-allocated memory, it could be a pointer to anything but your compiler probably doesn't realize this.

The compiler will create operator= for you but it will perform a shallow copy, not a deep copy.
In other words it will copy the pointer address of the data, it will not re-allocate space and copy the new'ed data.

An example:

#include <iostream>

class Test
{
	public:

	Test()
	{
		myData = new int;
		printf("Created data: 0x%08X\n", myData);
	}

	~Test()
	{
		printf("Destroying data: 0x%08X\n", myData);
		delete myData;
	}

	private:
	int* myData;
};

int main(int argc, char* argv[])
{
	Test test1;
	Test test2;

	test2 = test1;

	Test test3(test1);
}

This will produce output similar to:

Created data: 0x00333FC8
Created data: 0x00333148
Destroying data: 0x00333FC8
Destroying data: 0x00333FC8
Destroying data: 0x00333FC8

As you can see, this leaks memory (test2's data, 0x00333148), and triple-frees memory (0x00333FC8).

dewyatt
Newbie Poster
9 posts since Aug 2008
Reputation Points: 33
Solved Threads: 1
 

thanks for explanation through coding.

majesticmanish
Newbie Poster
14 posts since Dec 2008
Reputation Points: 10
Solved Threads: 0
 

No problem.
If there's anything you didn't understand, let me know!

dewyatt
Newbie Poster
9 posts since Aug 2008
Reputation Points: 33
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You