The code segment below compiles and, at startup, produces the result as:
$ make
gcc -g -Wall -o test test.c
$ ./test
string
/ * code1 * /
#include<stdio.h>
char *somefunc1()
{
char *temp="string";
return temp;
}
int main(int argc,char *argv[])
{
puts(somefunc1());
return 0;
}
while a small modification of this code gives different results:
$ make
gcc -g -Wall -o test test.c
test.c: In function ‘somefunc1’:
test.c:5: warning: function returns address of local variable
$ ./test
#include<stdio.h>
char *somefunc1()
{
char temp[] ="string";
return temp;
}
int main(int argc,char *argv[])
{
puts(somefunc1());
return 0;
}
Why is this happening?
source
share