Advertisement
Guest User

Untitled

a guest
Aug 16th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. char *getString()
  2. {
  3. char *str = "GfG"; /* Stored in read only part of shared segment */
  4.  
  5. /* No problem: remains at address str after getString() returns*/
  6. return str;
  7. }
  8.  
  9. int main()
  10. {
  11. printf("%s", getString());
  12. getchar();
  13. return 0;
  14. }
  15.  
  16. // The below program alse works perfectly fine as the string is stored in heap segment and
  17. // data stored in heap segment persists even after return of getString()
  18. char *getString()
  19. {
  20. int size = 4;
  21. char *str = (char *)malloc(sizeof(char)*size); /*Stored in heap segment*/
  22. *(str+0) = 'G';
  23. *(str+1) = 'f';
  24. *(str+2) = 'G';
  25. *(str+3) = '\0';
  26.  
  27. /* No problem: string remains at str after getString() returns */
  28. return str;
  29. }
  30. int main()
  31. {
  32. printf("%s", getString());
  33. getchar();
  34. return 0;
  35. }
  36.  
  37. // But, the below program may print some garbage data as string is stored in stack frame of function getString()
  38. // and data may not be there after getString() returns.
  39. char *getString()
  40. {
  41. char str[] = "GfG"; /* Stored in stack segment */
  42.  
  43. /* Problem: string may not be present after getSting() returns */
  44. return str;
  45. }
  46. int main()
  47. {
  48. printf("%s", getString());
  49. getchar();
  50. return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement