rs******@gmail.com writes:
I write a small program.
char *foo(void);
char *a = "I like C";
int main(void) {
if((strcmp(a,foo())) {
printf("\n i like c");
}
}
char *foo(void)
{
char b[100] = "I like C";
return b;
}
My teacher tells me that this program not work since the return value
from function foo() is not guaranteed to be preserved. I think this is
correct usage of pointers.
I dont think so. I think my teacher wrong.
As others have pointed out, your teacher is right.
Your array b is local to the function foo. As soon as foo returns,
the array ceases to exist, and any attempt to refer to it will invoke
undefined behavior.
You've probably been misled by the fact that the program *appears* to
work properly. That's the worst thing about undefined behavior; it's
not guaranteed to blow up. What probably happens in your program (for
a typical C implementation) is that the memory that the array occupied
is still there; it's just beyond the top of the stack. It *could* be
re-used for some other purpose. For example, an interrupt could be
triggered after foo() returns and before you use the value, clobbering
it. Or the system could mark the memory space as unavailable, causing
a trap when you try to access it. But the most likely thing is that
it's still right where you left it. Accessing it is still an error,
but the implementation isn't required to detect the error.
By returning from foo() you've told the system that you're finished
with the array. By attempting to use the array afterwards, you're
lying to the system. It's not obligated to show you any kind of
mercy. So don't do that.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.