void String::operator+=( String &pData)
{	
	int nLen = 0; // for store length of string

	// check string is null or not
	if(pData.m_pText != NULL)
	{
		// length of string
		nLen = (int) strlen(pData.m_pText);
	}	

	// Total string length
	int	nTotLen = m_nLength + nLen;

	//object of string class
	String Stemp;	

	//allocate memory
	Stemp.m_pText = new char[nTotLen + 1];

	// copy data
	strcpy(Stemp.m_pText, m_pText);	

	// append  string
	strcat(Stemp.m_pText, pData.m_pText);

	//allocate memory
	m_pText = new char[nTotLen + 1];

	// copy string
	strcpy(m_pText, Stemp.m_pText);

	// set new length
	m_nLength = nTotLen;
}

when i run this code heap memory leak found. why this memory leak come?
what i want to do avoid memory leak?

Recommended Answers

All 7 Replies

>> Stemp.m_pText = new char[nTotLen + 1];

where do you delete[] this memory? Perhaps you should start here

Stemp is a Class object so is i want to free the object?
is it destructor free the object?

Now i added delete[] Stemp.m-pText

at the end of the function.This time run time Heap memory exception is coming?.

Please help me?

You should delete the memory in the destructor of the class if the variable is a classmember.

Also: read the link I posted

First of all, the memory leak comes from this line:

m_pText = new char[nTotLen + 1];

Because before this line, m_pText already points to allocated memory, so you need to add a delete statement before:

if(m_pText)
  delete[] m_pText;
m_pText = new char[nTotLen + 1];

If you have also a similar delete statement in the destructor of String, then you don't need that "delete[] Stemp.m_pText" statement in this function, because when the function scope ends, the Stemp.m_pText will be deleted. That brings me to the heap memory exception you are getting. If you delete Stemp.m_pText and don't set it to NULL, when the destructor of Stemp executes (as the function scope ends) it will try to delete memory that has already been delete which will throw a heap memory exception, or worse, will corrupt the heap.

Thank you. Finally i got it.

when i dirctly set null value at the time it is working

m_pText = NULL;

-----------------------------------------------------------------------------------------

if(m_pText)
	{
		delete[] m_pText;
		
	}
	 m_pText = new char[nTotal + 1];

but in this case it is not working. run time heap memory exception is coming.

why it is like this? 
 please tell me....
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.