Skip to main content

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:

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:

The Exception Flow

Here's what happens when you try to access protected memory:

  1. CPU attempts to access the virtual memory address
  2. Memory Management Unit (MMU) checks page permissions
  3. OS has marked that page with "no access" permissions
  4. Hardware generates a page fault interrupt
  5. OS converts this interrupt into an access violation exception
  6. 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.