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; }- A. f2 and f3 only
- B. f1, f2 and f3
- C. f3 only
- 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
- Assume 32-bit unsigned int. What is printed? c unsigned int x = 65536; printf("%u %u", x x, x (x - 1) / 2);
- What is printed? c int i = 0; while (i++ < 5); printf("%d", i);
- What is printed? c #define LEVEL 2 #if LEVEL > 1 #define MSG "high" #elif LEVEL > 0 #define MSG "low" #endif #undef LEVEL #ifndef LEVEL…
- What is printed? c struct E { char name[8]; int age; }; struct E t[] = {{"Asha", 31}, {"Bilal", 27}, {"Chen", 45}, {"Dev", 22}}; struct E…
- What is printed? c int f(int a, int n) { if (n == 1) return a[0]; int m = f(a + 1, n - 1); return a[0] > m ? a[0] - m : m - a[0]; } int…
- What is printed? c printf("%.1f", 1 ? 3 : 2.5);