2013-04-02, 08:59 PM
Something to understand is that putting a negative number in an array is not what makes a program crash.
What do you think happens when you run the above code? Why?
[spoiler=Here's why]
data[i] is syntactic sugar for *(data + i). So it would be fetching *(data + sizeof(data)*i)
So, because of how the stack works in assembly, putting -1 in the array indice invades upon a different array.
One of the most powerful ideas of C is "trust the programmer". C doesn't care if you go outside of array bounds. It assumes that you know what the hell you're doing.
[/spoiler]
I would check elsewhere for your bug.
Code:
#include <stdio.h>
#include <Windows.h>
int main(void)
{
int data[5] = {0};
int moredata[5] = {0};
data[-1] = 20;
printf("%d\n", moredata[4]);
system("pause");
return 0;
}What do you think happens when you run the above code? Why?
Answer
[spoiler=Here's why]
data[i] is syntactic sugar for *(data + i). So it would be fetching *(data + sizeof(data)*i)
So, because of how the stack works in assembly, putting -1 in the array indice invades upon a different array.
One of the most powerful ideas of C is "trust the programmer". C doesn't care if you go outside of array bounds. It assumes that you know what the hell you're doing.
[/spoiler]
I would check elsewhere for your bug.
