E
Eric Moors
If have a question with respect to the code below:
#################################################################
#include <stdio.h>
char *ret_ok(void)
{
static char str[] = "explicit static";
return str;
}
char *ret_maybe(void)
{
return "implicit static";
}
char *ret_fails(void)
{
char str[] = "out-of-scope";
return str;
}
int main(void)
{
fprintf(stderr, "%s\n", ret_ok());
fprintf(stderr, "%s\n", ret_maybe());
fprintf(stderr, "%s\n", ret_fails());
return 0;
}
#################################################################
If I compile/run it, the following occurs.
#################################################################
/home/me>gcc -Wall -W -pedantic ret.c -o ret
ret.c: In function `ret_fails':
ret.c:19: warning: function returns address of local variable
/home/me>./ret
explicit static
implicit static
lÑ@ˆøÿ¿•À¹@pøÿ¿¨øÿ¿ËY@
##################################################################
I know that ret_fails() is incorrect, undefined behaviour.
from ret_ok() I know it is correct (but may have side-effects
when called more then once)
My question is about ret_maybe(). Is this defined behaviour or not?
I couldn't find it in the FAQ (the other two were in there) nor by
searching clc with google.
Eric
#################################################################
#include <stdio.h>
char *ret_ok(void)
{
static char str[] = "explicit static";
return str;
}
char *ret_maybe(void)
{
return "implicit static";
}
char *ret_fails(void)
{
char str[] = "out-of-scope";
return str;
}
int main(void)
{
fprintf(stderr, "%s\n", ret_ok());
fprintf(stderr, "%s\n", ret_maybe());
fprintf(stderr, "%s\n", ret_fails());
return 0;
}
#################################################################
If I compile/run it, the following occurs.
#################################################################
/home/me>gcc -Wall -W -pedantic ret.c -o ret
ret.c: In function `ret_fails':
ret.c:19: warning: function returns address of local variable
/home/me>./ret
explicit static
implicit static
lÑ@ˆøÿ¿•À¹@pøÿ¿¨øÿ¿ËY@
##################################################################
I know that ret_fails() is incorrect, undefined behaviour.
from ret_ok() I know it is correct (but may have side-effects
when called more then once)
My question is about ret_maybe(). Is this defined behaviour or not?
I couldn't find it in the FAQ (the other two were in there) nor by
searching clc with google.
Eric