2

I declared a multidimensional array in C, like so:

int arr[4][2];
int length = 0;

But I can apparently add as many elements as I want:

void addStuff(){
    arr[length][0] = someVal;
    arr[length++][1] = someVal;
}

and it doesn't give any errors. Does this mean I'm corrupting my memory somewhere in no-man's land? Or is this some feature of C I don't know about?

2
  • The only thing that prevents you from causing a big kernel panic is the fact that applications get their own personal address space these days. On the other hand, you will overwrite other variables in your own application, making it crash sooner or later. Commented Jun 15, 2012 at 14:34
  • 1
    @mihai Or depending on how the compiler and/or allocator lay out storage, you may not even overwrite your own variables, leading you to think the program is correct... Commented Jun 15, 2012 at 14:41

3 Answers 3

9

If you assign past the array size, you're definitely corrupting memory somewhere - the program may segfault, or other data may get corrupted, or it may (by accident) behave correctly. There's no bounds checking by default in C.

Sign up to request clarification or add additional context in comments.

Comments

2

You are definitely corrupting some memory. It will give you a wonderful error called "Undefined Behaviour" while executing the program.

In C it is your responsibility as a programmer to ensure that Out of Bound Array Write does not happen.

Comments

1

C doesn't have any array-bounds checking. So yes, you are manipulating memory somewhere. If you are lucky, that will immediately cause your program to crash. If you are unlucky, you are manipulating some valid data, causing a crash some time later, your program to work as before or your hard disk to get formatted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.