I have the following code:
char* p;
void func1()
{
p = "hello world";
}
int main()
{
func1();
printf(p);
return 0;
}
This code works fine here, but I'd like to know if it is correct or if there is an "undefined behavior" here.
Will the "hello world" still exist outside the func1()?
String literals are character arrays with static storage duration (cf. C11 6.4.5/6), and thus their lifetime extends to the end of the entire program. Your code is fine.
The answer is "yes" -- "hello world" will still exist outside of func1().
That's because the string literal is not actually being stored in func1's stack, but instead (usually) in a global table of such literals.
Two notes, however:
1) It is bad practice to do printf(str) even for a constant str -- if the string happens to contain a '%' character, then it will be interpreted as part of the format, printf will end up reading out of bounds and you'll get undefined behavior. Example:
char* str = "100% string!";
...
printf(str);
The important part is the % s part -- printf will interpret that as part of the format string, and expect another string in its arguments; since you didn't provide one, it will end up trying to dereference arbitrary memory and you will get undefined behavior.
What you can do instead is call printf like so:
printf("%s", str);
This is safe, as only the first argument is interpreted as the format string.
2) You do have a subtle undefined behavior elsewhere though(*note below) -- namely, the C standard demands that your output ends with a newline (\n) -- it doesn't have to be in the same printf call as your main string, but it has to come eventually.
So these are fine:
printf("hello, world");
printf("\n"); // can also just be "hello world\n"
//<program exit>
But this is not:
printf("hello, world");
//<program exit>
In practice, implementations don't have a problem with this, but it is annoying to the user when a program does not output that final newline, because then the terminal will print its own stuff after the program is done (user$ being the shell prompt here):
user$ ./hello-nl
hello, world
user$
vs. no newline:
user$ ./hello-nl
hello, worlduser$
(*note: to the best of my knowledge; it might be implementation-defined instead, though)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With