Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

arrays - Trying to understand what is wrong with the following code in C

I have a task to find why this code is wrong.

#include <stdlib.h>
#include <stdio.h>

#define fail(a)          ((test == 0 || test == a) ? fail##a() : 0)
#define N                (10)

int  a[N] = { 1 }; 
int* b = &a[0];


void fail1()

{
    printf("a[0] = %d
", a[0]);
    printf("b[0] = %d
", b[0]);
    printf("*b   = %d
", *b);
    *b = 2;
    a[N] = 3;
    printf("*b = %d
", *b);

}

...

int main(int argc, char **argv)
{
    int        test = 0;

    if (argc > 1) {
            sscanf(argv[1], "%d", &test);
            printf("doing test %d
", test);
    } else
            puts("doing all tests");

    fail(1);
    fail(2);
    fail(3);
    fail(4);
    fail(5);
    fail(6);

    puts("lab6 reached the end");

    exit(0);
}

By using valgrind it tells me that there is a fail in printf("*b = %d ", *b);. I have noticed that by commenting a[N] = 3; valvgrind gives no errors. But I do not understand why. I know that this has something to do with memory and I know that a[N] ask for element outside the array.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

C arrays have 0-based indexing. For an array defined like a[N], the maximum valid element will be a[N-1].

a[N] points to out of bound memory. Trying to access out of bound memory, invokes undefined behavior.

Now, while you may be knowing the above fact, what you might have ignored in the effect of UB. Once you hit UB, nothing is guaranteed. Simple solution, don't write a code which can invoke UB.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...