I\'m investigating a memory leak and from what I see, the problem looks like this:
int main(){
char *cp = 0;
func(cp);
//code
delete[] cp;
}
voi
As GMan and Neil mentioned, in order to work you will have to change func to:
char* func();
or void func(char*& p);
which will solve your immediate problem.
There is, however, a maintenance problem. In either case, func returns a pointer. What is not clear to the user of func is that returned pointer will have to be deleted. For this reason, generally avoid this construct unless 100% necessary. Rather:
So for C++ code,I would recommend:
class CBuf
{
public
CBuf()
{
iBuf = new char[100];
}
~CBuf
{
delete[] iBuf;
}
char* func()
{
//do stuff;
return iBuf;
}
private:
char* iBuf;
};
int main()
{
CBuf cb;
char* mychar = cb.func();
//do stuff with character array
//destructor gets called here because cb goes out of scope
}
However, in C programming especially, it might be 100% necessary to have some sort function to create the array. Therefore in C programming you can replace the destructor with a CreateCBuf
and DestroyCBuf
function. In this way the user of your library will know that the buffer returned needs to be destroyed.