Olba12 Olba12 - 10 months ago 42
C Question

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\n", a[0]);
printf("b[0] = %d\n", b[0]);
printf("*b = %d\n", *b);
*b = 2;
a[N] = 3;
printf("*b = %d\n", *b);



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

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


puts("lab6 reached the end");


By using valgrind it tells me that there is a fail in
printf("*b = %d\n", *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
ask for element outside the array.


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.