ProgrammingHardWipro · Cognizant pattern
What happens?
What happens?
int *getDangling(void) {
int local = 42;
return &local;
}
int main(void) {
int *p = getDangling();
printf("%d", *p);
}- A. It always prints 42 reliably
- B. Undefined behaviour: p is a dangling pointer to a local variable whose stack frame no longer exists after getDangling() returns
- C. Compilation error: cannot return the address of a local variable
- D. It always prints 0
Correct answer: B. Undefined behaviour: p is a dangling pointer to a local variable whose stack frame no longer exists after getDangling() returns
`local` has automatic storage duration tied to getDangling()'s stack frame, which is destroyed/invalidated once the function returns; p then points to memory that is no longer reserved for `local` (and may be reused by any later call), making *p undefined behaviour — it might coincidentally still show 42 on some runs, but this is never guaranteed.
More C Programming questions
- What happens? (Signed integer overflow.) c #include <limits.h> int main(void) { int x = INTMAX; int y = x + 1; printf("%d", y); }
- What happens? c int p = malloc(sizeof(int)); p = 10; free(p); printf("%d", p);
- What happens? c int divide(int a, int b) { return a / b; } int main(void) { printf("%d", divide(10, 0)); }
- What is printed? c #define DEBUG 0 int main(void) { #if DEBUG printf("debug moden"); #else printf("release moden"); #endif return 0; }
- Two files are compiled and linked together. What happens? c / file1.c / static int counter = 0; void inc(void) { counter++; } / file2.c /…
- What is printed? c int x = 10; void f(void) { int x = 20; { int x = 30; printf("%d ", x); } printf("%d ", x); } int main(void) { f()…