Reputation: 2877
I'd like to know why something like the C code below works in microcontrollers but not in mainstream computers:
// 1. Get memory location of GPIOA SET Register.
uint32_t *gpioa = (uint32_t *)(0x40020000 + 0x18);
// 2. Set bit to 1 to enable it.
*gpioa |= (1<<5);
Statement 1.
works on computers, but trying to access the memory location in any way leads to a segmentation fault.
Is the operating system blocking direct memory access in this way?
Upvotes: 1
Views: 694
Reputation: 58800
To add to Eric Postpischil's answer, the memory locations of various microcontroller registers are different for every model of microntroller you may try to program. So not only is your code not portable to a PC (where it segfaults), but it may also segfault or misbehave on a different microcontroller (unless it's the same family of microntroller, and they're specifically designed to be compatible).
Upvotes: 2
Reputation: 223747
Yes, on typical multi-user systems, the operating system controls access to memory.
Your process has only a virtual address space. The operating sets special registers or other features in the hardware to regulate your address space. Parts of your virtual address space are mapped to physical memory, and parts are not mapped at all. (A mapping specifies how a virtual address is translated to a physical address.) The operating system also determines whether you can read memory, write memory, or execute instructions from memory.
At times, the operating system may change what parts of memory your process can access. It may keep data your process is not currently using on disk and mark that part of your virtual address space inaccessible. When your process tries to access it, the hardware generates an exception, and the kernel handles the exception by reading the data from disk to memory, marking the memory accessible to your process, and restarting your process at the instruction that generated the exception.
Upvotes: 3