Is it safe to return "char*" from functions?

J

John Eskie

Hello,

I've seen in some programs that they provide functions which has the
following prototype:
char *func1();

However I'm not sure it's safe. If the char array beeing returned is a local
variable such as:

char *func1()
{
char string[] = "Hello World";
return string;
}

then you got a problem because the string will be stored on stack which will
be de-allocated upon function return. So in reality the string is located on
a memory position which is availble for anyones use.
If keywords such as static or global data is returned the situation might be
different.
If you use new/malloc on the data you want to return it's safe but then
again you're making a memory leak unless the caller knows it's nessecary to
clean up.

Could anyone clear this up for me.

Thanks in advance.

-- John
 
S

Spikinsson

"John Eskie"
then you got a problem because the string will be stored on stack which will
be de-allocated upon function return. So in reality the string is located on
a memory position which is availble for anyones use.
yes

If keywords such as static or global data is returned the situation might be
different.
uhu

If you use new/malloc on the data you want to return it's safe but then
again you're making a memory leak unless the caller knows it's nessecary to
clean up.

indeed
 
P

Peter van Merkerk

John Eskie said:
Hello,

I've seen in some programs that they provide functions which has the
following prototype:
char *func1();

However I'm not sure it's safe. If the char array beeing returned is a local
variable such as:

char *func1()
{
char string[] = "Hello World";
return string;
}

then you got a problem because the string will be stored on stack which will
be de-allocated upon function return. So in reality the string is located on
a memory position which is availble for anyones use.
If keywords such as static or global data is returned the situation might be
different.
If you use new/malloc on the data you want to return it's safe but then
again you're making a memory leak unless the caller knows it's nessecary to
clean up.

Could anyone clear this up for me.

It seems you understand the issues with returning pointers very well. The
C++ solution for this particular example is to return std::string instead of
a char pointer, and your resource management problems are solved.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top