Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

Function returning address of local variable error in C

I have the following code:

 char* gen()
 {
     char out[256];
     sprintf(out, ...); // you don't need to know what's in here I don't think

     return out;
 }

And I am getting this error when I try to compile:

ERROR: function returns address of local variable

I've tried having this return char[] and char with no luck. Am I missing something?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your char array variable out exists only inside the function's body.
When you return from the function, the content of out buffer can't be accessed anymore, it's just local to the function.

If you want to return some string from your function to the caller, you can dynamically allocate that string inside the function (e.g. using malloc()) and return a pointer to that string to the caller, e.g.

char* gen(void)
{   
    char out[256];
    sprintf(out, ...);

/* 
 *   This does NOT work, since "out" is local to the function.
 *
 *   return out;
 */

    /* Dynamically allocate the string */
    char* result = malloc(strlen(out) + 1) /* +1 for terminating NUL */

    /* Deep-copy the string from temporary buffer to return value buffer */
    strcpy(result, out);

    /* Return the pointer to the dynamically allocated buffer */
    return result;
    /* NOTE: The caller must FREE this memory using free(). */
}

Another simpler option would be to pass the out buffer pointer as a char* parameter, along with a buffer size (to avoid buffer overruns).

In this case, your function can directly format the string into the destination buffer passed as parameter:

/* Pass destination buffer pointer and buffer size */
void gen(char* out, size_t out_size)
{   
    /* Directly write into caller supplied buffer. 
     * Note: Use a "safe" function like snprintf(), to avoid buffer overruns.
     */
    snprintf(out, out_size, ...);
    ...
}

Note that you explicitly stated "C" in your question title, but you added a [c++] tag. If you can use C++, the simplest thing to do is to use a string class like std::string (and let it manage all the string buffer memory allocation/cleanup).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...