Returning pointers from functions

From: wonderboy (paul.rahul_at_gmail.com)
Date: 03/02/05


Date: 1 Mar 2005 23:05:11 -0800

Hey guys,
       I have a simple question. Suppose we have the following
functions:-

//-----My code starts here

char* f1(char* s)
{
        char* temp="Hi";
        return temp;
}

char* f2(char *s)
{
        char temp[100];
        strcpy(temp,"Hi");
        strcat(temp,s);
        return temp;
}

//-----My code ends here

Now, suppose I have a main function which calls the both. Thing is,
when i compile the prog, the compiler gives me a warning regarding f2
saying that temp is a local variable and i m returning its address.

str1.cpp: In function `char* f2(char*)':
str1.cpp:14: warning: address of local variable `temp' returned

This is fine and expected. But y dont i get the same warning for f1? At
runtime, everything works fine although i guess this is not right as
the memory for the local variables can get overwritten anytime. Pls,
can someone clarify the whole concept. TIA.

Cheers

PS- if this has been discussed already, pls provide the link and my
apologies in dat case.



Relevant Pages