원문 정보
1. 데브코아 (http://cafe.naver.com/devcore/243, http://cafe.naver.com/devcore/244)
2. http://superkkt.com/229
3. http://en.wikipedia.org/wiki/Memory_alignment
4. http://en.wikipedia.org/wiki/Bus_error
인용
특정 CPU에서는 정렬되지 않은 메모리 주소에 접근(read or write)하려고 하면 BUS error가 발생한다.
여기서 특정 CPU라고 언급을 했는데 일반적으로 SPARC 같은 RISC 계열 CPU는 정렬되지 않은 메모리 주소에 접근 할 수 없고, x86 같은 CISC 계열은 접근이 가능하다. 그리고 정렬되지 않은 주소란 뜻은 CPU's memory-alignment rules의 배수에 해당하지 않는 메모리 주소를 뜻한다.
우리가 일반적으로 사용하는 x86 CPU는 프로그램이 정렬되지 않은 메모리 주소에 접근할 경우 정렬된메모리 주소를 사용해서 앞 ,뒤 메모리를 두 번 읽고, mask와 shift 과정을 거쳐서 프로그램이 요청한 메모리의 값을 돌려준다. 반면에 SPARC CPU는 바로 BUS error를 발생시켜서 프로그램이 종료된다.
하지만 CPU가 정렬되지 않은 메모리 주소에 접근 할 수 없다고 해서 메모리를 바이트 단위로접근 할 수 없다는 뜻은 아니다. 대 부분의 CPU(x86, SPARC, 기타 등등)는 메모리 주소에 바이트단위 접근을 허용한다. 하지만 위에서 x86 CPU가 정렬되지 않은 메모리에 주소에 접근하는 방법과 마찬가지로 데이터 버스 사이즈만큼 메모리를 읽어 들여서 mask, shift 과정을 거쳐서 바이트 단위로 메모리 값을 참조 할 수 있다. 하지만 이 방법은 비효율적이다. 그러나 문자열을 다루는 프로그램처럼 바이트 단위 처리가 꼭 필요한 경우에는 어쩔 수 없이 메모리에 바이트 단위로 접근을 해야 한다.
그럼 바이트 단위로 메모리에 접근이 가능한데 언제 BUS error가 발생하는 걸까? 한마디로 요약하면
아래와 같다.
"정렬되지 않은 메모리 주소에 바이트 단위로 접근하는 것은 허용되지만, 그 이상의 사이즈를 가지는타입으로 접근하면 BUS error가 발생한다."
There are two main causes of bus errors:
- non-existent address
- The CPU is instructed by software to read or write a specific physical memory address. Accordingly, the CPU sets this physical address on its address bus
and requests all other hardware connected to the CPU to respond with
the results, if they answer for this specific address. If no other
hardware responds, the CPU raises an exception, stating that the requested physical address is unrecognised by the whole computer system. Note that this only covers physical memory addresses. When software tries to access an undefined virtual memory address, that is generally considered to be a segmentation fault rather than a bus error, though if the MMU is separate, the processor can't tell the difference.
- unaligned access
- Most CPUs are byte-addressable, where each unique memory address refers to an 8-bit byte.
Most CPUs can access individual bytes from each memory address, but
they generally cannot access larger units (16 bits, 32 bits, 64 bits
and so on) without these units being "aligned"
to a specific boundary, such as 16 bits (addresses 0, 2, 4 can be
accessed, addresses from 1, 3, 5, are unaligned) or 32 bits (0, 4, 8,
12 are aligned, all addresses in-between are unaligned). Attempting to
access a value larger than a byte at an unaligned address can cause a
bus error.