ProgrammingHardIBM · Deloitte pattern

What happens when this runs?

What happens when this runs?
char *p;
{
    char buf[20] = "hello";
    p = buf;
}
printf("%s", p);
  1. A. It reliably prints hello
  2. B. It prints an empty string
  3. C. Undefined behaviour: p dangles once buf's scope ends and its storage is reclaimed
  4. 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

Exams that ask this topic