In my program, i have line like this:
const char * str = getStr();
Do i need to call destructor on str [] at the end of function to prevent memory leaks?
It all depends on what getStr()
does. It may even be that you have to call free
on the pointer if getStr()
created it with malloc
. It may be that getStr()
is returning a pointer to a static area (not very thread safe, but it happens) or any number of other things.
Part of the contract and documentation for getStr()
should be who owns the pointer it returns.
Here are some examples of possible getStr()
functions...
In this case getStr()
owns the pointer and you don't have to do anything to free it. OTOH, what's being pointed at may change the next time you call getStr()
so you should probably make your own copy if you need to keep it around for any length of time:
const char *getStr()
{
static char buf[30] = "Silly counter";
buf[0] = buf[0] + 1;
return buf;
}
In this case, you will eventually need to call free
on the pointer returned:
const char *getStr()
{
return strdup("Silly string");
}
In this case, you will need to call plain old delete
on the pointer returned:
const char *getStr()
{
return new char;
}
In this case, you will need to call delete []
on the pointer returned:
const char *getStr()
{
return new char[50];
}
There are many other possibilities. As I stated previously, part of the contract for a function (which should appear in its documentation) is who owns the pointer returned and how that data pointed to must be disposed of if doing so is the caller's responsibility.
Question does not contain enough information to tell, it depends what getStr()
does. For example:
const char *getStr() {
return "boo";
}
then you must not call delete.
const char *getStr() {
return new char;
}
then you should call delete str;
to avoid a memory leak (and must not call delete[]
).
const char *getStr() {
return new char[10];
}
then you should call delete[] str;
to avoid a memory leak (and must not call delete
).
const char *getStr() {
return 0;
}
then it doesn't matter what you do, calling any kind of delete
on str
has no effect.
Ownership of resources, and how to release any resources owned, are part of the interface to a function, and should be documented at the same time as you document what the return value actually is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With