# C/C++: Bus error (core dumped) — SIGBUS from misaligned access or a bad memory-mapped file

**Code:** `Bus error` · **Category:** C/C++ · **Seen on:** C/C++, Linux, macOS

The CPU or OS rejected a memory access that is not a plain invalid address: misaligned data, or touching a memory-mapped file page that no longer exists.

## Meaning

SIGBUS differs from SIGSEGV: the address may be valid but the access is not allowed. On ARM and SPARC, misaligned reads of `int` or `double` raise it; on x86 and macOS it more often comes from `mmap`: the file was truncated, the disk filled up, or the file lives on a removed network share. Writing to a string literal on some platforms also produces it.

## Common causes

- `mmap`ed file truncated or deleted while the program reads it
- Disk full or quota exceeded when writing to an mmap'ed or sparse file
- Misaligned pointer cast (`*(int*)(buf + 1)`) on strict-alignment CPUs
- Writing into a string literal or read-only mapping
- Stack alignment problems in hand-written assembly

## Quick fix

1. Check file size before and while using `mmap` and handle `SIGBUS` carefully
2. Use `memcpy` to read unaligned values instead of casting the pointer
3. Never modify string literals — copy them to a `char[]`

## Detailed fix by platform

### Linux

1. Verify space: `df -h` and `ls -l` the mapped file
2. `gdb ./app` → `bt` shows the access that faulted

### macOS

1. Bus error: 10 often means a write to read-only memory or a truncated mapped file

## Code examples

### Safe unaligned read

```cpp
#include <cstdint>
#include <cstring>

uint32_t read_u32(const unsigned char* p) {
    uint32_t v;
    std::memcpy(&v, p, sizeof v);      // safe for any alignment
    return v;                          // *(uint32_t*)p could raise SIGBUS on strict CPUs
}
```

## How to diagnose

1. **Mapping** — Is a mmap'ed file involved?
2. **Disk** — Is the disk full?
3. **Alignment** — Any pointer cast to a wider type?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/bus-error)
