ProgrammingHardHCL · Tech Mahindra pattern
Assume a 64-bit LP64 ABI. What happens when this runs?
Assume a 64-bit LP64 ABI. What happens when this runs?
int *create(void) {
int x = 42;
return &x;
}
int main(void) {
int *p = create();
printf("%d", *p);
}- A. It prints 0
- B. Compile-time error: cannot return the address of a local variable
- C. It prints 42, guaranteed by the C standard
- D. Undefined behaviour: p is a dangling pointer to x's destroyed stack frame
Correct answer: D. Undefined behaviour: p is a dangling pointer to x's destroyed stack frame
x is a local (automatic) variable whose storage is reclaimed as soon as create() returns. The returned pointer dangles, pointing at memory that is no longer reserved for x; dereferencing it is undefined behaviour (it may happen to print 42 on some setups, but that is not guaranteed and is not something to rely on).
More C Programming questions
- Assume a 64-bit LP64 ABI. What is printed? c int a[3] = {1, 2, 3}; int p = a; printf("%d ", p++); printf("%d ", ++p); printf("%d", p);
- Assume a 64-bit LP64 ABI. What is printed? c int a = 5; int p1 = &a; int p2 = &a; printf("%d ", p1 == p2); printf("%d", p1 == p2);
- Assume a 64-bit LP64 ABI. What is printed? c int a[2][3] = {{1, 2, 3}, {4, 5, 6}}; int p = (int )a; for (int i = 0; i < 6; i++)…
- Assume a 64-bit LP64 ABI (natural alignment, no #pragma pack). What is printed? c struct A { char c; int i; char d; }; struct B { int i…
- Assume a 64-bit LP64 ABI. What is printed? c union U { int i; char c[4]; double d; }; printf("%zu", sizeof(union U));
- Assume a little-endian 64-bit machine. What is printed? c union U { int i; char bytes[4]; }; union U u; u.i = 0x01020304; printf("%x %x %x…