Archived

This topic is now archived and is closed to further replies.

Zeke

Memory Leaks?

Recommended Posts

I need to know more about memory leaks. I know what causes them (i.e. allocating memory with new and not freeing that memory with delete[]), however I must be missing something because even when i delete[] to free the memory boundschecker still moans about memory leaking. For example I have a function that returns a char* so I do this: char* cPtr=GetCharPtr(); char * GetCharPtr() { char* cPtr2=new char[Length]; //read file into cPtr2 return cPtr2; } //do other stuff with cPtr delete[]cPtr; cPtr=NULL I delete[] as soon as I dont need cPtr anymore and yet boundschecker says I have a memory leak of 6,811,112bytes originating at line: char* cPtr2=new char[Length]; I cannot delete[] any sooner because I still need to use it. For example I start my app and do something that starts off the GetCharPtr func and then do a load of other stuff with the returned char*. I need to keep the cPtr until I hit save where the app then writes cPtr to disk and delete[]cPtr. Am I missing something here? Because I figured if I delete[] it then the memory is freed and everything is fine but boundschecker tells me its not. Sorry for the long post. If anyone can help me I would be most appreciated Cheers

Share this post


Link to post
Share on other sites
Are you sure that''s the only place you''re calling that function? Are you sure you''re not accidentally copying the returned string, and then deleting the copy and not the original?

In my experience, BoundsChecker is seldom wrong about leaks; when it is wrong, it is usually about statics.

If you''re leaking that much memory (that''s quite a bit), and you have process diagnostics tools, you should be able to see your memory usage go up as the program executes. This would corroborate BC''s story.

Share this post


Link to post
Share on other sites
Thanks for the reply.

I have no claims that BC is wrong as im pretty much a newbie to programming and especially new/delete so i''d have thought its something im doing wrong rather than BC reporting wrong.

Im pretty sure im not copying the string not in any of the places that BC is reporting leaks. I have a lot of functions that return a * created with new and in some case the function returns a * that is created in another function that returns a *, if you see what i mean:

char* Func1()
{
return Func2()
}

char* Func2
{
char* ptr=new char[length]
return ptr;
}
mainFunction()
{
char* ptr=Func1();
//do stuff
delete[]ptr;
}

and I think in some cases ive even got third or fourth functions that return the char* created in the fourth func.

But everywhere I am just doing
char* ptr=FuncThatReturnsCharPtr().
In none of the functions do i return a copy of the created *.

Thanks for the input.


Share this post


Link to post
Share on other sites