This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Classic C problems, need help!


Hello,
if you have for example a function declared as:
void f( const char*);
you can be quite sure that the function doesn't alter your string.
On the outher hand:
void g( char*);
may alter your string (modify the data, call free(), ...) that must clarify 
the documentation. If g doesn't alter the string it is a bad style to omit 
the const.

To return a string there are two possibilities:
1. The receiver has to free the memory
2. The function takes care about the memory stuff
	Example:
	const char* f()
	{
		static char* c [SIZE]'
		return c;
	}
But method 2. is not reentrant.

On Friday 03 May 2002 19:42, you wrote:
> Hello,
>
> Please forgive me if this is off topic as I don't know where to ask it.
> I am having the hardest time with this and was wondering if anyone can
> give me some tips.  I have a function that I want to perform some
> operations and return a string.  This string will never be assigned to a
> variable, merely only passed to a function.  What that function does
> with it I have no idea.
>
> So at first I thought well why not just return a char * which has been
> newed.  Well the problem with this is if I don't assign it to a
> variable, then how do I delete it?  And if I do assign it to a variable,
> and I pass the variable to the function, how do I know that if I delete
> it, the function won't go trying to use that again?  I mean, does the
> function have to actually take care of making a copy of it first?
>
> Ok, so if I choose to do this.  If I create a char array in my function,
> say char sting1[20]; and then I assign the value to it, and do a return
> string1; I know that it is out of scope once the function returns, but
> doesn't it stay alive for at least a second like when it is returned and
> passed as an unamed variable to another function?
>
> Of course I don't have this problem with returning integers, but with
> strings I don't understand.  If you return something and don't give it a
> name, such as a string, how can it be dynamic, and yet you delete it if
> you have nothing to delete it with?
>
> I know to the trained C veteran, this sounds stupid, but this is the
> only area I've struggled with in C and c++, and would hope that someone
> on here can give me some insight into this and explain the proper ways
> to return strings from a function and not have to worry about it
> dissapearing.  Thank you very much.
>
> Dime


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]