Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- char *getString()
- {
- char *str = "GfG"; /* Stored in read only part of shared segment */
- /* No problem: remains at address str after getString() returns*/
- return str;
- }
- int main()
- {
- printf("%s", getString());
- getchar();
- return 0;
- }
- // The below program alse works perfectly fine as the string is stored in heap segment and
- // data stored in heap segment persists even after return of getString()
- char *getString()
- {
- int size = 4;
- char *str = (char *)malloc(sizeof(char)*size); /*Stored in heap segment*/
- *(str+0) = 'G';
- *(str+1) = 'f';
- *(str+2) = 'G';
- *(str+3) = '\0';
- /* No problem: string remains at str after getString() returns */
- return str;
- }
- int main()
- {
- printf("%s", getString());
- getchar();
- return 0;
- }
- // But, the below program may print some garbage data as string is stored in stack frame of function getString()
- // and data may not be there after getString() returns.
- char *getString()
- {
- char str[] = "GfG"; /* Stored in stack segment */
- /* Problem: string may not be present after getSting() returns */
- return str;
- }
- int main()
- {
- printf("%s", getString());
- getchar();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement