KatInterview

C Pointers, printf Format Specifiers, and Memory Segments

System DesignModel answer
EasyModel answerSystem DesignCpointersmemory-layout

Last updated

Test your grasp of C pointer semantics, how printf interprets variadic arguments, and where different kinds of data live in a process's memory layout.

Setup

Consider this C declaration:

const char *c = "12345";

Assume a typical 64-bit Linux or macOS system compiled with GCC or Clang, unless the behavior in question is undefined or implementation-defined.


Part 1 — Format Specifiers and printf

For each call below, state what the programmer probably intended and what actually happens at runtime. Where behavior is undefined, say so and describe what you would typically observe on x86-64:

printf("%s", c);
printf("%d", c);
printf("%c", c);
printf("%c", *c);
printf("%c", *(c+1));

Also: what is the correct way to print the address stored in c?


Part 2 — Debugger Inspection

Assuming the binary was compiled with -g -O0, show how you would use gdb or lldb to:

  • Display the value of c as an address
  • Examine the raw bytes stored at that address
  • Print the null-terminated string starting at that address

Part 3 — Memory and Allocation

3a. Compare malloc/free (C) with new/delete (C++). Cover at least: initialization behavior, constructor/destructor calls, type safety, failure modes, array variants, and mixing rules.

3b. Describe the main segments of a typical process's address space — text, data, BSS, heap, and stack — and what kind of data belongs in each. Where does the string literal "12345" live, and where does the pointer variable c live when it is declared locally vs. globally?

Hints

Hint 1

printf is variadic: it has no knowledge of the actual argument types. It reads arguments from registers or the stack based solely on what the format string says. A mismatch between the specifier and the actual type is undefined behavior, not just a wrong output.

Hint 2

For the debugger part, think about three distinct goals: show an address (a single 64-bit value), show raw memory bytes (useful for seeing the null terminator and ASCII codes), and show a string (high-level interpretation). Each has its own command.

Hint 3

A string literal is baked into the binary at compile time and lives in a read-only segment. The pointer variable that holds its address is a separate object that lives wherever its declaration scope puts it — local scope means the stack, file scope means the data segment.