Re: using local buffers.

From: Herbert Kremser (kremser@flinux.tu-graz.ac.at)
Date: 09/15/95


On Thu, 14 Sep 1995, Scatter wrote:

> > Btw, I know I can 'return "string"' in order to return a string from a 
> > char* function, but if I have a local buffer, how would I return a string 
> > in the same manner without returning the address of the local buffer?
> 
> char *some_fun(char *str){
>     char my_buf[SOME_LENGTH];
> 
>     strcpy(my_buf, str);
>     return(strdup(my_buf));
> }
> 
> A worthless piece of code that should answer your question.
> 
> /*  I hate posting code, cuz I'm just too damn insecure :) */
> 
> 

I guess it's not a good idea to post such code without comments in this
list. From my experience there are some C newbies in this group too,
and your "solution" could lead them to some mistakes.

First, the strcpy in your example is rather useless, as the declaration
of the variable my_buf, but well, the question was how to return a local
buffer.  :)

But you shouldn't forget to mention for C-newbies, that strdup allocates
memory for the string, and therefore needs to be free'd if it's no longer
needed.

I guess the original poster didn't want to allocate memory, but rather
wants what is called a static variable.

char *some_fun(int secret)
{
  static char my_buf[SOME_LENGTH];

  sprintf(my_buf, "The secret number is %d.", secret);
  return  my_buf;
}

Herbert

[on public request 12 lines of signature deleted]  *snip* ;)



This archive was generated by hypermail 2b30 : 12/07/00 PST