The first problem here is in the code
total[0]+=a[j];
total[1]+=b[j];
total[2]+=c[j];
where you're using total[n]
s un-initialized. They contain indeterminate values and using them invokes undefined behavior.
To elaborate, total
being an uninitialized automatic local variable, the initial values of the elements of the array are indeterminate. By using the +=
operator on those elements, you're trying to read (use) the values which are indeterminate, so it invokes UB in your case.
Related quote from C11
, chapter §6.5.16.2, Compound assignment,
A compound assignment of the form E1 op= E2
is equivalent to the simple assignment
expression E1 = E1 op (E2)
, except that the lvalue E1
is evaluated only once, and with
respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation. If E1
has an atomic type, compound assignment is a
read-modify-write
operation with memory_order_seq_cst
memory order
semantics.
So, by using the +=
on an uniniitilized value, _you're trying to read (or use) a variable with indeterminate value, which causes the UB.
If you want, you can initialize the whole array by using a syntax like
int total[3] = {0};
which initializes all elements of the array to 0, which is what basically you were expecting.
That said, void main(void)
is not a conforming signature for main()
in a hosted environment, as per the spec, it should be int main(void)
, at least.