ProgrammingHardIBM · Deloitte pattern
What happens when this runs?
What happens when this runs?
int f(void) {
int x = 5;
return x;
}
int *g(void) {
int y = 10;
return &y;
}
int main(void) {
int *p = g();
printf("%d %d", f(), *p);
}- A. 5 10, both guaranteed
- B. 5 10, but only by coincidence; *p is undefined behaviour since y's storage no longer belongs to y
- C. Compile-time error: g() cannot return the address of a local variable
- D. Undefined behaviour affects both f() and g() equally
Correct answer: B. 5 10, but only by coincidence; *p is undefined behaviour since y's storage no longer belongs to y
f() simply returns a copy of x's value, which is perfectly fine and always well-defined. g() returns the ADDRESS of its local y, whose storage is reclaimed the instant g() returns; dereferencing that dangling pointer via *p is undefined behaviour, even though it may 'happen to' still show 10 on many systems since the stack memory hasn't been overwritten yet.
More C Programming questions
- What happens when this runs? c char buf[5]; strcpy(buf, "hello world"); printf("%s", buf);
- What happens when this runs? c int divide(int a, int b) { return a / b; } int main(void) { printf("%d", divide(10, 0)); }
- What happens when this runs? c int p = (int )malloc(3 sizeof(int)); if (p == NULL) { return 1; } p[0] = 1; p[1] = 2; p[2] = 3; free(p)…
- What happens when this runs? c int arr[10]; for (int i = 0; i <= 10; i++) { arr[i] = i; } printf("done");
- What is printed? c #define CONCAT(a, b) a##b int main(void) { int xy = 100; printf("%d", CONCAT(x, y)); }
- What is printed? c #if defined(FEATUREX) && !defined(FEATUREY) #define MODE 1 #elif !defined(FEATUREX) #define MODE 2 #else #define MODE 3…