TIL: 0xC0000005
After writing a piece of code for socket programming using UDP and TCP protocols, I was feeling pretty confident about my implementation. I ran the program and BOOM 💥
Exception thrown at 0x0008FFA47EEAFB8 (mswsock.dll) in MyApp.exe:
0xC0000005: Access violation reading location 0x0000000000000001
The crash occurred here:
auto optVal = int { 1 };
if (setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, (char*)optVal, sizeof(int))) { ... }
The Root Cause
What address am I actually passing to setsockopt()
? That's the core issue.
I'm casting optVal
's value to char*
instead of taking the address of the variable.
Here's what's happening step by step:
optVal
is 1(char*)optVal
casts the integer value 1 to a pointer, effectively passing memory address0x0000000000000001
as the buffersetsockopt()
attempts to read from memory address0x0000000000000001
, which triggers the access violation
The Fix
auto optVal = int { 1 };
if (setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, (char*)&optVal, sizeof(int))) { ... }
//------------------------------------------------------^
Or more cleanly with explicit casting:
auto optVal = int { 1 };
if (setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&optVal), sizeof(optVal))) { ... }
Why Low Memory Addresses Are Protected
The problem with accessing memory location 0x0000000000000001
(or any very low address) stems from how operating systems implement memory protection:
Low memory addresses (0x00000000 - 0x0000FFFF) are intentionally protected by the OS:
- These addresses reside in what's called the "null pointer region" or "low memory guard zone"
- Windows (and most modern operating systems) mark these memory pages as inaccessible
- Any attempt to read from or write to these addresses triggers a hardware memory protection fault
The Exception Flow
Here's what happens when you try to access protected memory:
- CPU attempts to access the virtual memory address
- Memory Management Unit (MMU) checks page permissions
- OS has marked that page with "no access" permissions
- Hardware generates a page fault interrupt
- OS converts this interrupt into an access violation exception
- Your program crashes with
0xC0000005
(ACCESS_VIOLATION)
This protection mechanism helps catch common programming errors like null pointer dereferences and prevents accidental corruption of critical system memory regions.
- ← Previous
Convert Hex to Decimal in Bash - Next →
TIL: nano zone abandoned