Pointer Indirection, Format Specifiers, and Process Segments in C

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

Consider the following C variable declaration inside a function compiled with GCC or Clang on a standard 64-bit Linux or macOS machine:

const char *c = "2468";

Walk through the questions below, explicitly distinguishing behavior guaranteed by the C standard from undefined or platform-specific behavior:

  1. Format specifiers and pointer indirection: For each call below, state what the author likely meant to output and explain what actually happens at run time:

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

      Then show the standard-compliant way to print the memory address stored in c.

  2. Interactive debugging with gdb and lldb: Show the debugger commands you would run to inspect:

    • the hexadecimal address held by c,
    • the individual byte values stored beginning at that address, and
    • the NUL-terminated character sequence starting there.
  3. Dynamic allocation and virtual memory layout:

    • Contrast malloc / free in C against new / delete in C++ across type checking, initialization, constructor/destructor execution, out-of-memory handling, and array forms.
    • Outline what data is placed in the text, read-only data, initialized data, BSS, heap, and stack regions of a process, and identify where both c and "2468" live.

Scope & Expectations

  • Distinguish pointer value from pointee bytes: Clearly separate the 8-byte pointer variable c from the read-only character array "2468" (including its trailing '\0' byte) and explain how variadic printf arguments interact with mismatched format specifiers.
  • Practical debugger fluency: Give concrete gdb or lldb commands (and memory-examination flags) that distinguish &c, c, raw byte dumps, and C-string views.
  • Systems-level memory rigor: Cover lifetime, initialization, and deallocator pairing rules for C vs. C++ heap allocation, and accurately map source constructs to virtual memory segments and page permissions.

Step-by-step walkthrough

  1. Picture what `const char *c = "2468";` puts in memory

    Every part of this question clicks once you separate two distinct things in memory: the string literal's bytes, and the pointer variable c that stores their starting address.

    Read-only data segment (.rodata on Linux / __TEXT,__cstring on macOS):
      Address:   A       A+1     A+2     A+3     A+4
      Hex byte:  0x32    0x34    0x36    0x38    0x00
      ASCII:     '2'     '4'     '6'     '8'     '\0'   <-- NUL terminator
    
    Pointer variable `c` (8 bytes on 64-bit Linux/macOS, e.g. on the stack):
      +----------------------------+
      |   A (e.g. 0x555555556010)  |  ---> points to byte '2' at address A
      +----------------------------+
    

    Three sizes summarize the difference on 64-bit Linux and macOS: - sizeof(c) is 8: c is a 64-bit pointer, regardless of how long the string is. - sizeof("2468") is 5: four visible ASCII characters plus the trailing '\0' (NUL terminator, the zero byte that marks the end of a C string). - strlen(c) is 4: strlen walks from address A counting bytes until it hits 0x00.

    In C, "2468" is a static array of 5 chars (type char[5] in C, const char[5] in C++). Assigning an array to c triggers array-to-pointer decay (the compiler automatically converts the array expression into the address of its first element, &"2468"[0]).

  2. Why `printf` trusts the format string blindly

    printf is a variadic function (a function declared with ..., as in int printf(const char *fmt, ...), so it accepts any number and types of trailing arguments). Because the parameter list after fmt has no fixed types, the C compiler does not convert a pointer into an int just because you wrote "%d". It only applies C's default argument promotions (char and short widen to int; float widens to double) and places the raw values in registers or stack slots.

    At run time, printf reads arguments strictly according to %s, %d, %c, or %p. If the actual argument type does not match what the specifier expects, the C standard says the result is undefined behavior (C11 7.21.6.1, paragraph 9 — meaning the language gives zero guarantees: it can print garbage, crash, or change across compiler flags). Modern compilers warn about these bugs when -Wformat is enabled (on by default in Clang, and included in -Wall in GCC).

  3. Walk through the five `printf` calls

    Assume c holds a typical 64-bit Linux address A = 0x555555556010, where A stores '2' (0x32 = 50) and A + 1 stores '4' (0x34 = 52):

    Call Intended meaning What actually happens
    printf("%s", c); Print the string "2468" Well-defined. %s expects a char * (or const char *), reads bytes starting at A (0x32, 0x34, 0x36, 0x38) until it sees 0x00, and prints 2468.
    printf("%d", c); Print the address in decimal (or mistakenly print "2468" as 2468) Undefined behavior. %d expects a 32-bit signed int, not a 64-bit pointer. In practice on x86-64 and arm64, it interprets the low 32 bits of the address as a signed 32-bit integer (1431658512 for 0x555555556010, or a negative number if bit 31 is 1).
    printf("%c", c); Print the first character '2' (forgot *) Undefined behavior. %c expects an int character code, not a pointer. In practice it takes the lowest byte of the address (0x10 here) and writes that raw byte — usually invisible or garbled terminal output.
    printf("%c", *c); Print the first character '2' Well-defined. *c dereferences c (reads the value stored at address A), getting char '2' (50), promoted to int 50, which %c prints as 2.
    printf("%c", *(c + 1)); Print the second character '4' Well-defined. Pointer arithmetic c + 1 advances by 1 * sizeof(char) = 1 byte to A + 1; *(c + 1) (identical to c[1]) reads '4' (52), promoted to int 52, printing 4.

    Here is the exact bit math showing what happens in practice on little-endian 64-bit Linux/macOS when c = 0x555555556010:

    addr = 0x555555556010
    
    # "%d" reads only the low 32 bits (0x55556010) as a signed 32-bit integer:
    low32 = addr & 0xFFFFFFFF
    signed32 = low32 - (1 << 32) if low32 >= (1 << 31) else low32
    print(signed32)           # 1431658512 (or negative if bit 31 of addr is 1!)
    
    # "%c" keeps only the lowest 8 bits (0x10):
    print(hex(addr & 0xFF))   # 0x10 (ASCII Data-Link-Escape control character)
    

    Why the low bytes? On x86-64 Linux, the second argument is passed in the 64-bit register rsi, and reading a 32-bit int reads its lower half esi. On Apple Silicon macOS (arm64), variadic arguments go onto the stack in 8-byte slots, and on a little-endian CPU (least-significant byte stored at the lowest address), reading 4 bytes from that slot also fetches the low 32 bits.

  4. Print the pointer address the right way

    Use %p, which is the format specifier dedicated to object pointers, and cast c to (const void *) (or (void *)):

    printf("%p\n", (const void *)c);   /* e.g. 0x555555556010 on Linux, 0x100003f9a on macOS */
    

    Why include the cast? The C standard specifies %p for a pointer to void. Although char * and void * share the same byte representation in C, pedantic compiler modes check the exact type, and (const void *)c satisfies both -Wpedantic and -Wcast-qual without dropping const.

    If you specifically want to format the address as an integer (for example, zero-padded hex), convert it to uintptr_t from <stdint.h> and use the matching <inttypes.h> macro:

    #include <inttypes.h>
    #include <stdint.h>
    
    printf("0x%" PRIxPTR "\n", (uintptr_t)c);
    

    Avoid printf("%lx", (unsigned long)c): long is 64 bits on 64-bit Linux/macOS (LP64) so it appears to work there, but on 64-bit Windows (LLP64) long is only 32 bits and silently truncates pointers! Also note that printf("%s", c) without '\n' stays buffered in stdout until a newline, fflush(stdout), or normal program exit — if the program crashes right after, nothing may appear on screen.

  5. Inspect the address, raw bytes, and string in `gdb` and `lldb`

    Compile with debug symbols and optimization turned off (gcc -g -O0 demo.c or clang -g -O0 demo.c) so c is not optimized away, set a breakpoint in main, and step past const char *c = "2468";:

    # In GDB (typical on Linux):
    (gdb) break main
    (gdb) run
    (gdb) next
    (gdb) print/x c           # 1) Value of c as a hex address: $1 = 0x555555556010
    (gdb) print &c            #    (Contrast: address of pointer variable c itself on the stack!)
    (gdb) x/5xb c             # 2) 5 raw bytes in hex:  0x32  0x34  0x36  0x38  0x00
    (gdb) x/5cb c             #    Same 5 bytes as chars: '2' '4' '6' '8' '\000'
    (gdb) x/s c               # 3) NUL-terminated string starting at c: "2468"
    (gdb) info proc mappings  # Shows which memory mapping holds 0x555555556010 and its r--p perms
    

    In GDB, x stands for examine memory: /5xb requests 5 units in x (hexadecimal) of size b (1 byte), and /s reads a NUL-terminated C string.

    # In LLDB (default on macOS):
    (lldb) breakpoint set --name main
    (lldb) run
    (lldb) next
    (lldb) p/x c                                            # 1) Value of c as a hex address
    (lldb) frame variable c                                 #    Shows type, address, and string preview
    (lldb) memory read --size 1 --format x --count 5 c      # 2) 5 raw bytes: 0x32 0x34 0x36 0x38 0x00
    (lldb) memory read --format c-string c                  # 3) String starting at c: "2468"
    (lldb) image lookup --address 0x100003f9a               #    Shows section (__TEXT,__cstring)
    

    LLDB also supports GDB's shorthand x/5xb c and x/s c directly. Note that ASLR (Address Space Layout Randomization, an OS security feature that randomizes segment base addresses on each run) changes exact addresses across runs, though debuggers disable ASLR by default for reproducible debugging.

  6. Compare `malloc`/`free` vs `new`/`delete` and map process memory segments

    malloc/free vs new/delete

    malloc/free are C library functions that allocate and release raw untyped bytes; new/delete are C++ language operators that create and destroy typed objects with full lifetime management.

    Aspect malloc / free (C, also callable in C++) new / delete (C++ only)
    Argument Byte count: malloc(4 * sizeof(int)) Type (and optional args): new int[4], new Widget(5)
    Return type & safety void * (implicit conversion in C; requires cast in C++) Exact T *, checked by the compiler
    Initialization Uninitialized garbage bytes (calloc(n, sz) zero-fills) Calls constructor; new int is indeterminate, new int() zero-initializes
    Cleanup Releases bytes only; never runs destructors Calls destructor first, then releases storage
    Failure behavior Returns NULL (caller must check!) Throws std::bad_alloc (new (std::nothrow) T returns nullptr)
    Arrays malloc(n * sz) can overflow; calloc(n, sz) checks overflow new T[n] must be freed with delete[], never plain delete
    Resizing / customization Resizable via realloc No realloc (use std::vector); overloadable operator new/delete

    Never mix families (free on new, delete on malloc, or scalar delete on new[] — all are undefined behavior), and never allocate non-trivial C++ classes like std::string with malloc because their constructors never run. In modern C++, prefer RAII wrappers (std::vector, std::string, std::make_unique) over manual new/delete.

    Process memory segments and where "2468" lives

    High virtual addresses
    +-------------------------------------------------------------------+
    | Stack      Per-thread call frames: local variables, parameters,   |
    |   |        return addresses; grows downward (~8 MiB default)      |
    |   v                                                               |
    |            (Shared libraries & large mmap regions live in between)|
    |   ^                                                               |
    |   |                                                               |
    | Heap       Dynamic allocations from malloc / calloc / new         |
    +-------------------------------------------------------------------+
    | BSS        Zero- or uninitialized globals and `static` variables  |
    +-------------------------------------------------------------------+
    | Data       Globals and `static` variables with non-zero init      |
    +-------------------------------------------------------------------+
    | Rodata     Read-only constants & string literals like "2468"      |
    +-------------------------------------------------------------------+
    | Text       Compiled machine instructions (read + execute, shared) |
    +-------------------------------------------------------------------+
    Low virtual addresses
    

    Where everything in const char *c = "2468"; lives: - The 5 bytes '2','4','6','8','\0' of "2468" live in the read-only data segment (.rodata in Linux ELF binaries; __TEXT,__cstring inside the read-only __TEXT segment in macOS Mach-O binaries) for the entire lifetime of the program. Attempting ((char *)c)[0] = 'X'; is undefined behavior and crashes with SIGSEGV / SIGBUS because those virtual memory pages lack write permission. - The 8-byte pointer variable c itself lives on the stack (or solely in a CPU register) if declared inside a function, or in the data segment if declared at file scope or static. (By contrast, char buf[] = "2468"; inside a function allocates a writable 5-byte array on the stack and copies the bytes '2','4','6','8','\0' into it.)

Intuition & how it works

Think of const char *c = "2468"; as two separate physical items: a row of 5 locked display cases on a museum wall holding '2', '4', '6', '8', and '\0' (a NUL terminator, the zero byte that marks where a C string ends), plus a slip of paper c in your pocket with the museum wall's street address written on it (a pointer, a variable whose value is a memory address).

Beginners often assume C functions inspect what you pass and convert it automatically, the way Python's print() formats strings and numbers alike. That mental model fails in C because printf is a variadic function (a function taking ... whose extra arguments have no fixed types in its signature): printf is essentially blindfolded and reaches into the argument slot expecting whatever byte width and meaning your % format specifier promised. Handing printf an 8-byte address when "%d" or "%c" told it to read a 4-byte integer triggers undefined behavior (a rule violation where the C standard makes zero guarantees about what the program does).

Trace what happens on 64-bit Linux when "2468" sits at read-only address 0x555555556010 (0x32, 0x34, 0x36, 0x38, 0x00) and c holds 0x555555556010: 1. printf("%s", c) follows address 0x555555556010 and prints characters up to 0x00 -> 2468. 2. printf("%d", c) (mismatched!) grabs only the low 32 bits 0x55556010 as a signed integer -> 1431658512 (garbage decimal, not the full 64-bit address and not 2468). 3. printf("%c", c) (mismatched!) grabs the lowest byte 0x10 of the address -> an unprintable control byte, whereas printf("%c", *c) dereferences c (reads the byte stored at that address, 0x32) -> 2, and printf("%c", *(c + 1)) steps 1 byte forward (0x34) -> 4. 4. printf("%p\n", (const void *)c) uses the pointer specifier -> 0x555555556010.

Key points

  • Pointer vs string literal storage: "2468" is a 5-byte static array (sizeof("2468") == 5, strlen(c) == 4) stored in read-only memory (.rodata on Linux, __TEXT,__cstring on macOS). c is an 8-byte pointer (sizeof(c) == 8 on 64-bit LP64 systems) holding that array's starting address via array-to-pointer decay (automatic conversion of an array expression into a pointer to element 0).
  • Exact verdict on the five printf calls: %s with c (2468), %c with *c (2), and %c with *(c + 1) (4) are completely well-defined; %d with c and %c with c pass a const char * where an int is required and are undefined behavior (in practice printing the truncated low 32 bits as a signed int and the lowest 8 bits of the address as a raw byte, respectively).
  • Printing addresses portably: Always use printf("%p\n", (const void *)c); (or (uintptr_t)c with PRIxPTR from <inttypes.h> when treating the address as an integer).
  • Inspecting in gdb and lldb: Print the address stored in c with p/x c (frame variable c in lldb), inspect all 5 raw bytes including '\0' with x/5xb c (or memory read --size 1 --format x --count 5 c), and display the NUL-terminated string with x/s c (or memory read --format c-string c).
  • malloc/free vs new/delete: malloc/free manage raw uninitialized byte blocks (void *, return NULL on failure, never run constructors or destructors); new/delete create and destroy typed C++ objects (T *, run constructors to initialize objects and destructors to clean up resources, throw std::bad_alloc on failure, and require delete[] for new[]).
  • Process memory layout: Machine code sits in text (read/execute); string literals and const globals sit in rodata (read-only); non-zero initialized globals/statics sit in data; zero/uninitialized globals/statics sit in BSS (Block Started by Symbol, a zero-initialized static segment that takes almost no space in the binary file on disk); dynamic allocations live in the heap; per-thread call frames and local variables live on the stack.

Common mistakes

  • Claiming printf("%d", c) "prints the pointer address in decimal": It is undefined behavior, and on 64-bit platforms int is only 32 bits wide, so the top 32 bits of the 64-bit address are silently discarded (and addresses with bit 31 set print as negative numbers).
  • Using %lx or %lu with (unsigned long)c to print pointers: Works by accident on 64-bit Linux/macOS where long is 8 bytes, but truncates the top 32 bits on 64-bit Windows where long is 4 bytes; %p with (const void *)c is portable everywhere.
  • Confusing c, *c, and &c: c is the address of '2' (for %s or %p), *c is the character '2' itself (for %c), and &c is the stack/data address where the 8-byte variable c lives. Passing *c (50) to %s makes printf dereference address 0x32 and crash with a segmentation fault!
  • Thinking p + 1 always adds 1 byte: Pointer arithmetic scales by sizeof(*p). c + 1 adds 1 byte only because sizeof(char) == 1; for an int *p, p + 1 advances by sizeof(int) (4 bytes).
  • Saying "2468" is allocated on the stack or heap: String literals have static storage duration in read-only memory for the whole life of the process; only char buf[] = "2468"; inside a function copies those 5 bytes onto the stack.
  • Mixing C/C++ deallocators (free after new, delete after malloc, or delete after new[]): All are undefined behavior and routinely corrupt allocator metadata or skip destructors.

Follow-up questions

  • *How does the memory layout and behavior change if c is declared inside main as char c[] = "2468"; rather than const char c = "2468";? c becomes a 5-byte writable char array allocated directly on main's stack frame and initialized by copying '2','4','6','8','\0' from read-only memory. Now sizeof(c) is 5 instead of 8, c[0] = '9'; is completely legal, and c = "other"; fails to compile because arrays cannot be reassigned. When passed to printf, c still decays to &c[0], so %s, *c, and *(c + 1) print the exact same output, while %p now prints a stack address instead of a .rodata address.
  • *What happens at compile time and run time if code casts away constness and executes ((char )c)[0] = '9';? The explicit cast suppresses the ordinary type error (though -Wcast-qual warns that const was discarded), so compilation succeeds unless warnings are treated as errors. At run time, modifying a string literal is undefined behavior in both C and C++: on modern 64-bit Linux and macOS, the OS maps .rodata / __TEXT,__cstring hardware pages without write permission, so the CPU raises a page-protection fault and terminates the process (SIGSEGV on Linux, SIGBUS or SIGSEGV on macOS).
  • Which compiler flags and runtime sanitizers would you enable in CI to catch printf format mismatches and allocator misuse automatically? Enable strict compiler diagnostics (-Wall -Wextra -Wformat=2 -Wcast-qual -Werror) and annotate any custom printf-style wrappers with __attribute__((format(printf, 1, 2))) so GCC and Clang check every format string at compile time. In test builds, enable AddressSanitizer (-fsanitize=address) and UndefinedBehaviorSanitizer (-fsanitize=undefined), which catch out-of-bounds accesses, use-after-free, leaks, and new[]/delete or malloc/delete mismatches immediately with exact stack traces.

Follow-up questions

Similar questions

More Arista interview questions

All 5 Arista questions →