ProgrammingHardIBM · Deloitte pattern
What happens when this runs?
What happens when this runs?
char *p;
{
char buf[20] = "hello";
p = buf;
}
printf("%s", p);- A. It reliably prints hello
- B. It prints an empty string
- C. Undefined behaviour: p dangles once buf's scope ends and its storage is reclaimed
- D. Compile-time error: buf cannot be assigned to a pointer outside its scope
Correct answer: C. Undefined behaviour: p dangles once buf's scope ends and its storage is reclaimed
buf is a local array confined to the inner block; once that block ends, its storage is no longer reserved (on a typical stack-based implementation it may be overwritten by other code). p still holds that now-invalid address, so dereferencing it via %s is undefined behaviour — it might happen to still show 'hello' by luck, but that is never guaranteed.
More C Programming questions
- What happens when this runs? c int a[5] = {1, 2, 3, 4, 5}; a[5] = 100; printf("%d", a[5]);
- What happens when this runs? c int p = NULL; printf("%d", p);
- What happens when this runs? c int p = malloc(sizeof(int)); free(p); printf("%d", p);
- What happens when this runs? c int f(void) { int x = 5; return x; } int g(void) { int y = 10; return &y; } int main(void) { int p = g()…
- 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)); }