Program 1
|
Program 2
|
char *getString()
{ char str[] = "Will I be printed?"; return str; } int main() { printf("%s", getString()); getchar(); } |
char *getString()
{ char *str = "Nice test for strings"; return str; }
int main()
{ printf("%s", getString()); getchar(); return 0; } |
- The former prints garbage because str is a local array allocated on the stack which is destroyed after the stack frame for getString() is popped.
- In the latter case, str is a pointer that points to a global data section, which does not get affected with pushing/popping off stack frames
- There is no heap allocation in the second program. Strings are stored in the global read-only segment
No comments:
Post a Comment