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:
-
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.
-
Interactive debugging with
gdbandlldb: 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.
- the hexadecimal address held by
-
Dynamic allocation and virtual memory layout:
- Contrast
malloc/freein C againstnew/deletein 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
cand"2468"live.
- Contrast
Scope & Expectations
- Distinguish pointer value from pointee bytes: Clearly separate the 8-byte pointer variable
cfrom the read-only character array"2468"(including its trailing'\0'byte) and explain how variadicprintfarguments interact with mismatched format specifiers. - Practical debugger fluency: Give concrete
gdborlldbcommands (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
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
cthat 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)is8:cis a 64-bit pointer, regardless of how long the string is. -sizeof("2468")is5: four visible ASCII characters plus the trailing'\0'(NUL terminator, the zero byte that marks the end of a C string). -strlen(c)is4:strlenwalks from addressAcounting bytes until it hits0x00.In C,
"2468"is a static array of5chars (typechar[5]in C,const char[5]in C++). Assigning an array toctriggers array-to-pointer decay (the compiler automatically converts the array expression into the address of its first element,&"2468"[0]).Why `printf` trusts the format string blindly
printfis a variadic function (a function declared with..., as inint printf(const char *fmt, ...), so it accepts any number and types of trailing arguments). Because the parameter list afterfmthas no fixed types, the C compiler does not convert a pointer into anintjust because you wrote"%d". It only applies C's default argument promotions (charandshortwiden toint;floatwidens todouble) and places the raw values in registers or stack slots.At run time,
printfreads 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-Wformatis enabled (on by default in Clang, and included in-Wallin GCC).Walk through the five `printf` calls
Assume
cholds a typical 64-bit Linux addressA = 0x555555556010, whereAstores'2'(0x32 = 50) andA + 1stores'4'(0x34 = 52):Call Intended meaning What actually happens printf("%s", c);Print the string "2468"Well-defined. %sexpects achar *(orconst char *), reads bytes starting atA(0x32, 0x34, 0x36, 0x38) until it sees0x00, and prints2468.printf("%d", c);Print the address in decimal (or mistakenly print "2468"as2468)Undefined behavior. %dexpects a 32-bit signedint, 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 (1431658512for0x555555556010, or a negative number if bit 31 is1).printf("%c", c);Print the first character '2'(forgot*)Undefined behavior. %cexpects anintcharacter code, not a pointer. In practice it takes the lowest byte of the address (0x10here) and writes that raw byte — usually invisible or garbled terminal output.printf("%c", *c);Print the first character '2'Well-defined. *cdereferencesc(reads the value stored at addressA), gettingchar'2'(50), promoted toint50, which%cprints as2.printf("%c", *(c + 1));Print the second character '4'Well-defined. Pointer arithmetic c + 1advances by1 * sizeof(char) = 1byte toA + 1;*(c + 1)(identical toc[1]) reads'4'(52), promoted toint52, printing4.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-bitintreads its lower halfesi. 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.Print the pointer address the right way
Use
%p, which is the format specifier dedicated to object pointers, and castcto(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
%pfor a pointer tovoid. Althoughchar *andvoid *share the same byte representation in C, pedantic compiler modes check the exact type, and(const void *)csatisfies both-Wpedanticand-Wcast-qualwithout droppingconst.If you specifically want to format the address as an integer (for example, zero-padded hex), convert it to
uintptr_tfrom<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):longis 64 bits on 64-bit Linux/macOS (LP64) so it appears to work there, but on 64-bit Windows (LLP64)longis only 32 bits and silently truncates pointers! Also note thatprintf("%s", c)without'\n'stays buffered instdoutuntil a newline,fflush(stdout), or normal program exit — if the program crashes right after, nothing may appear on screen.Inspect the address, raw bytes, and string in `gdb` and `lldb`
Compile with debug symbols and optimization turned off (
gcc -g -O0 demo.corclang -g -O0 demo.c) socis not optimized away, set a breakpoint inmain, and step pastconst 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 permsIn GDB,
xstands for examine memory:/5xbrequests 5 units in x (hexadecimal) of size b (1 byte), and/sreads 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 candx/s cdirectly. 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.Compare `malloc`/`free` vs `new`/`delete` and map process memory segments
malloc/freevsnew/deletemalloc/freeare C library functions that allocate and release raw untyped bytes;new/deleteare 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 compilerInitialization Uninitialized garbage bytes ( calloc(n, sz)zero-fills)Calls constructor; new intis indeterminate,new int()zero-initializesCleanup 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) Treturnsnullptr)Arrays malloc(n * sz)can overflow;calloc(n, sz)checks overflownew T[n]must be freed withdelete[], never plaindeleteResizing / customization Resizable via reallocNo realloc(usestd::vector); overloadableoperator new/deleteNever mix families (
freeonnew,deleteonmalloc, or scalardeleteonnew[]— all are undefined behavior), and never allocate non-trivial C++ classes likestd::stringwithmallocbecause their constructors never run. In modern C++, prefer RAII wrappers (std::vector,std::string,std::make_unique) over manualnew/delete.Process memory segments and where
"2468"livesHigh 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 addressesWhere everything in
const char *c = "2468";lives: - The 5 bytes'2','4','6','8','\0'of"2468"live in the read-only data segment (.rodatain Linux ELF binaries;__TEXT,__cstringinside the read-only__TEXTsegment in macOS Mach-O binaries) for the entire lifetime of the program. Attempting((char *)c)[0] = 'X';is undefined behavior and crashes withSIGSEGV/SIGBUSbecause those virtual memory pages lack write permission. - The 8-byte pointer variablecitself 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 orstatic. (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 (.rodataon Linux,__TEXT,__cstringon macOS).cis an 8-byte pointer (sizeof(c) == 8on 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 element0). - Exact verdict on the five
printfcalls:%swithc(2468),%cwith*c(2), and%cwith*(c + 1)(4) are completely well-defined;%dwithcand%cwithcpass aconst char *where anintis 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)cwithPRIxPTRfrom<inttypes.h>when treating the address as an integer). - Inspecting in
gdbandlldb: Print the address stored incwithp/x c(frame variable cinlldb), inspect all 5 raw bytes including'\0'withx/5xb c(ormemory read --size 1 --format x --count 5 c), and display the NUL-terminated string withx/s c(ormemory read --format c-string c). malloc/freevsnew/delete:malloc/freemanage raw uninitialized byte blocks (void *, returnNULLon failure, never run constructors or destructors);new/deletecreate and destroy typed C++ objects (T *, run constructors to initialize objects and destructors to clean up resources, throwstd::bad_allocon failure, and requiredelete[]fornew[]).- Process memory layout: Machine code sits in text (read/execute); string literals and
constglobals 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 platformsintis 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
%lxor%luwith(unsigned long)cto print pointers: Works by accident on 64-bit Linux/macOS wherelongis 8 bytes, but truncates the top 32 bits on 64-bit Windows wherelongis 4 bytes;%pwith(const void *)cis portable everywhere. - Confusing
c,*c, and&c:cis the address of'2'(for%sor%p),*cis the character'2'itself (for%c), and&cis the stack/data address where the 8-byte variableclives. Passing*c(50) to%smakesprintfdereference address0x32and crash with a segmentation fault! - Thinking
p + 1always adds1byte: Pointer arithmetic scales bysizeof(*p).c + 1adds1byte only becausesizeof(char) == 1; for anint *p,p + 1advances bysizeof(int)(4bytes). - 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; onlychar buf[] = "2468";inside a function copies those 5 bytes onto the stack. - Mixing C/C++ deallocators (
freeafternew,deleteaftermalloc, ordeleteafternew[]): 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";?
cbecomes a 5-byte writablechararray allocated directly onmain's stack frame and initialized by copying'2','4','6','8','\0'from read-only memory. Nowsizeof(c)is5instead of8,c[0] = '9';is completely legal, andc = "other";fails to compile because arrays cannot be reassigned. When passed toprintf,cstill decays to&c[0], so%s,*c, and*(c + 1)print the exact same output, while%pnow prints a stack address instead of a.rodataaddress. - *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-qualwarns thatconstwas 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,__cstringhardware pages without write permission, so the CPU raises a page-protection fault and terminates the process (SIGSEGVon Linux,SIGBUSorSIGSEGVon 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 customprintf-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, andnew[]/deleteormalloc/deletemismatches immediately with exact stack traces.
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";?
- What happens at compile time and run time if code casts away constness and executes ((char *)c)[0] = '9';?
- Which compiler flags and runtime sanitizers would you enable in CI to catch printf format mismatches and allocator misuse automatically?
Similar questions
- Raw-Storage Generic C++ Stack and Lifetime Semantics
- Missing Integer in a Sorted Step-One Sequence
- Delete Matching Nodes from a Singly Linked List
- Palindrome Verification and Skipped-Number Search
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target