Confused - returning local variable value

Hi all,

I know that one is not supposed to try to return the value of a variable local to a function because the variable "goes away" at the end of the function.

As I understand it, the following is wrong:

char *testfunc (void)
{
    char buffer [8];
    sprintf (buffer, "%s\n", "Hello");
    return buffer;
}

The above may or may not work, but it's "wrong" because "buffer" goes away when "testfunc" ends, so it returns a pointer to memory which USED to contain ASCII "Hello" but is not guaranteed to because "buffer" no longer exists.

If this is all true, then why is the following OK:

int testfunc (void)
{
    int sum = 0;
    sum += 1;
    sum += 2;
    return sum;
}

So then why does THIS work?

This is basic stuff... but all of a sudden I started thinking about it and ended up confusing myself. I'm sure I'll kick myself in the behind when I get the answer......

Thanks!

-- Roger

You are in essence are trying returning an array. In C you can't return the value of an array, only the pointer of it. Your array is local to the function, meaning it only exists in that function, so you're trying to pass back a pointer of something that may not exist.

It's easier to modify an array

char str[8];
insertVal(str);

void insertVal(*in_str) {
   strcpy(in_str, "hello");

}

Better still to use references, rather than pointers....

Regards,
Ray L.

The return value of a function is passed back to the caller in a register, NOT memory. So, even though the functions stack frames has gone away, and perhaps been over-written, the return value is still perfectly intact for the caller to use. When you "return" a complex data type, like an array or struct, a pointer to that array is returned to the caller in a register. The array itself exists on the functions stack frame, which may, or may not, still be intact after the function returns. So if the caller tries to access the array through the returned pointer, though the pointer is still pointing at the location in memory where the array was, the array itself may, or may not, still be intact.

Regards,
Ray L.