C Pointers, printf Format Specifiers, and Memory Segments
System DesignModel answerLast 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
cas 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.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Format Specifiers
c is an 8-byte pointer holding the address of the first byte of the six-byte, read-only sequence '1' '2' '3' '4' '5' '\0'. The core insight: printf is variadic. It cannot inspect the types of its arguments; it reads them according to the format string. A mismatch is undefined behavior (UB).
| Call | What is passed | What the specifier expects | Outcome |
|---|---|---|---|
printf("%s", c) | const char * | char * | Correct. Walks bytes until '\0', prints 12345. |
printf("%d", c) | const char * (8 bytes) | int (4 bytes) | UB. On x86-64 SysV, the pointer arrives in rsi; %d reads esi (the low 32 bits), printing some meaningless integer like 1431658500. |
printf("%c", c) | const char * | int (via unsigned char) | UB. %c treats the lowest byte of whatever it reads as a character code, producing a likely unprintable byte. |
printf("%c", *c) | char promoted to int | int | Correct. Dereferences the pointer and prints 1 (ASCII 49). |
printf("%c", *(c+1)) | char promoted to int | int | Correct. Pointer arithmetic moves one byte forward; prints 2. Same as c[1]. |
GCC and Clang both flag the UB cases with -Wformat (part of -Wall). A strong answer says "this is UB, the compiler warns, and in practice you see address bits" — not "it prints X."
Printing the address correctly:
printf("%p\n", (void *)c); /* %p is defined for void* */
printf("0x%" PRIxPTR "\n", (uintptr_t)c); /* portable hex digits */
The (void *) cast is technically required; %p is only defined for void *, and the standard does not guarantee other pointer types share its representation.
Part 2 — Debugger Inspection
Compile with -g -O0 to prevent c from being optimized away.
| Goal | gdb | lldb |
|---|---|---|
Value of c as address | p c or p/x c | frame variable c or p c |
| Raw bytes at address | x/6xb c | memory read -s1 -fx -c6 c |
| String at address | x/s c | memory read -f s c |
For the raw-bytes case, x/6xb c on gdb shows something like:
0x100003f6a: 0x31 0x32 0x33 0x34 0x35 0x00
Two details that demonstrate real understanding: 0x31 is ASCII '1', and 0x00 is the null terminator. The mapping containing that address will appear read-only (r--p) in /proc/<pid>/maps, which is why writing through c raises SIGSEGV.
Part 3a — malloc/free vs new/delete
| Aspect | malloc / free | new / delete |
|---|---|---|
| Language | C; usable in C++ | C++ only |
| Size computation | Caller: malloc(n * sizeof(T)) | Compiler: new T[n] |
| Return type | void * — requires a cast in C++, so not type-safe | T * — type-safe |
| Initialization | None (garbage). calloc zero-fills. | Calls constructor. new T() value-initializes; new T leaves POD types indeterminate. |
| Cleanup | free releases bytes only | delete calls destructor then releases |
| Failure | Returns NULL | Throws std::bad_alloc. Use new (std::nothrow) for a nullptr return instead. |
| Arrays | No distinction in the API | new[] must pair with delete[]. The runtime stores a count ("cookie") to run N destructors. |
| Resize | realloc available | No equivalent; use std::vector. |
| Customization | Global interposition only | operator new overloadable globally or per class; placement new constructs into pre-existing memory. |
| Null operand | free(NULL) is a no-op | delete nullptr is a no-op |
The cardinal rule: never mix the two. free on new-allocated memory, delete on malloc memory, and delete on new[] memory are all undefined behavior. In modern C++ you rarely write either directly — prefer std::unique_ptr, std::make_unique, and containers.
Part 3b — Memory Segments
| Segment | Typical contents | Properties |
|---|---|---|
.text | Compiled machine instructions | Read + execute, shared across processes |
.rodata | String literals, const globals, jump tables | Read-only, usually adjacent to text |
.data | Non-zero-initialized globals and statics | Read-write, stored in the binary |
.bss | Zero-initialized or uninitialized globals and statics | Zero-filled at load; takes no file space |
| Heap | malloc/new allocations | Grown via brk/mmap; managed by the allocator |
| Stack | Locals, return addresses, saved registers | One per thread, LIFO, grows downward, typically 8 MB on Linux |
Where "12345" and c live:
- The literal bytes
'1' '2' '3' '4' '5' '\0'live in.rodata, mapped read-only. The linker may merge identical literals, so two occurrences of"12345"can share a single address. - When
cis a local variable, the 8-byte pointer sits on the stack. Whencis a global, it sits in.data(it is non-zero, being a valid address).
Writing through the pointer with ((char *)c)[0] = 'X' is UB and typically causes SIGSEGV, because the page is mapped read-only.
Contrast with char a[] = "12345". That declares a writable 6-byte array; the literal's bytes are copied into it at initialization. If a is local, those bytes live on the stack and are fully mutable. Note that sizeof a == 6 while sizeof c == 8.
Common Mistakes
- Claiming a specific output for the UB cases rather than calling them UB.
- Forgetting the
(void *)cast with%p. - Mixing
deletewithmallocorfreewithnew— these are all UB even if they "work" on a given allocator. - Saying the string literal lives on the stack — it does not; only the pointer variable does (when local).
- Assuming
new intzero-initializes — it does not unless you writenew int().