ProgrammingVery hardProduct company OA · GATE CS

Which of these functions return a pointer that is still valid to read after the function returns?

Which of these functions return a pointer that is still valid to read after the function returns?
char *f1(void) { char s[] = "hi"; return s; }
char *f2(void) { char *s = "hi"; return s; }
char *f3(void) { static char s[] = "hi"; return s; }
char *f4(void) { char *s = malloc(3); strcpy(s, "hi"); free(s); return s; }
  1. A. f2 and f3 only
  2. B. f1, f2 and f3
  3. C. f3 only
  4. D. f2 only

Correct answer: A. f2 and f3 only

f1 returns the address of a local array that dies with the call, and f4 returns memory it has already freed: both dangle. f2 returns a pointer to a string literal, which has static storage duration (read-only, but valid). f3's static array also lives for the whole program.

More C Programming questions

Exams that ask this topic