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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…