ProgrammingHardProduct-company MCQ pattern
What is printed? (undefined behavior aside, assume typical stack layout where locals of adjacent calls can overlap after return)
What is printed? (undefined behavior aside, assume typical stack layout where locals of adjacent calls can overlap after return)
int *dangling(void) {
int local = 42;
return &local;
}
int main(void) {
int *p = dangling();
int x = 7;
printf("%d", *p);
}- A. Always prints 42
- B. Always prints 7
- C. Undefined behavior: p points to a local variable whose lifetime ended when dangling() returned
- D. Compilation error: cannot return the address of a local
Correct answer: C. Undefined behavior: p points to a local variable whose lifetime ended when dangling() returned
local's storage duration ends when dangling() returns, so p is a dangling pointer; dereferencing it is undefined behavior even though it compiles cleanly (compilers typically only warn).
More C Programming questions
- What is printed? c char arr[] = {"one", "two", "three"}; char p = arr; printf("%s %c %s", p, ((p + 1) + 1), p[2]);
- What is printed? Assume 32-bit int. c int flags = 0; flags |= (1 << 2); flags |= (1 << 4); flags &= ~(1 << 2); printf("%d", flags);
- What can be said about this program? c #include <stdlib.h> int main(void) { int p = malloc(sizeof(int)); free(p); free(p); }
- What is printed? c void modify(int arr[10]) { printf("%lu ", sizeof(arr)); } int main(void) { int a[10]; printf("%lu ", sizeof(a))…
- What is printed? const qualifies what p points to, not p itself. c int x = 5, y = 10; const int p = &x; p = &y; printf("%d", p);
- What is printed? c int a = 10; int p = &a; int q = p; p = NULL; printf("%d", q);