Computerfunda is blog about education in computer science. It provides resources for cometitive examinations like GATE, UGC NET etc. You can get everything related to cs is for free

Responsive Ads Here

Tuesday 16 May 2017

Why these two programs behave in a different way?

Consider the following  two C language program snippet given below in the table:
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;
}


  why these two programs behave in a different way:
  • 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
For an in-depth understanding of these things, I'd suggest to read this book: Computer Systems: A Programmer's Perspective and this excellent course on MIT OCW on code optimization: Performance Engineering of Software Systems

No comments:

Post a Comment

What you need for Analysis of algorithms?

What you need for analysis of algorithms: First of all, you need to understand what is an algorithm is ? an algorithm is involved in eve...