开发者

where is the bug of this C code

I was told this is a buggy code, but I don't know why, some could explain it to me. why there would not be an array out of bound exception when I compile?

int a[10];
int j;

void main () {
    int i, 开发者_如何学运维j = 42;
    for (i = 0; i <=10; i++) a[i] = i;
    printf("%d", j);
}


You've allocated 10 spaces. You fill 11.


Change

int a[10];

to

int a[11];

or

for (i = 0; i <=10; i++) a[i] = i;

to

for (i = 0; i < 10; i++) a[i] = i;

You've created an array with a count of 10 and try to put 11 elements in it. You either need to put only 10 elements in it or create a bigger array.


Here's one bug:

void main () {

should be

int main (int argc, char** argv) {

Another bug is in your loop. You write past the end of array a, and if your compiler placed j in memory immediately following a (which based on your question I assume it did), then the out-of-bounds array access will actually end up assigning a value to j. Hence, when you write 10 into a[10] (which doesn't exist), you are writing it into the memory where j lives (causing this to act like j = 10). However, this behavior is dependent on how your compiler lays out the variables in memory, so you may very well see different behavior if you compiled the same program on a different platform.


filling array crossing the boundary...a[10] is wrong.


There should not be an overflow of array, thats correct as you have mentioned in your question. But some compilers will give a PASS with the code whereas others will trigger a warning (or error is elevated).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜