I recently finished reading about virtual memory and I have a question about how malloc works within the Virtual address space and Physical Memory.
For example (code copied from another SO post)
void main(){
int *p;
p=malloc(sizeof(int));
p[500]=999999;
printf("p[0]=%d\n",p[500]); //works just fine.
}
Why is this allowed to happen? Or like why is that address at p[500] even writable?
Here is my guess.
When malloc is called, perhaps the OS decides to give the process an entire page. I will just assume that each page is worth 4KB of space. Is that entire thing marked as writable? That's why you can go as far as 500*sizeof(int) into the page (assuming 32bit system where int is size of 4 bytes).
I see that when I try to edit at a larger value...
p[500000]=999999; // EXC_BAD_ACCESS according to XCode
Seg fault.
If so, then does that mean that there are pages that are dedicated to your code/instructions/text segments and marked as unwrite-able completely separate from your pages where your stack/variables are in (where things do change) and marked as writable? Of course, the process thinks they're next to each order in the 4gb address space on a 32-bit system.
It occurs when the index used to address array items exceeds the allowed value. It's the area outside the array bounds which is being addressed, that's why this situation is considered a case of undefined behavior. Absence of array overrun control in C and C++ is the factor that makes this error possible.
ArrayIndexOutOfBoundsException may occur if an array is accessed out of bounds. But there is no such functionality in C and undefined behaviour may occur if an array is accessed out of bounds.
Master C and Embedded C Programming- Learn as you go But, if we use index which is greater than 3, it will be called as an index out of bounds. If, we use an array index which is out of bounds, then the compiler will compile and even run.
There is no bounds checking because it is simply exposing raw memory. Implementing a robust bounds-checking mechanism would have been almost impossible in C. In C++, bounds-checking is possible on class types. But an array is still the plain old C-compatible one.
"Why is this allowed to happen?" (write outside of bounds)
C does not require the additional CPU instructions that would typically be needed to prevent this out-of-range access.
That is the speed of C - it trusts the programmer, giving the coder all the rope needed to perform the task - including enough rope to hang oneself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With