Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it that we can write outside of bounds in C?

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.

like image 285
Arrow Avatar asked Mar 19 '15 02:03

Arrow


People also ask

What is out of bound in C?

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.

What happens if an array goes out of bounds?

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.

Does C have index 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.

Why array bounds checking is not available in C?

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.


1 Answers

"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.

like image 58
chux - Reinstate Monica Avatar answered Oct 10 '22 05:10

chux - Reinstate Monica