Reputation: 3
I'm experiencing some strange C behavior. I have an array (that I have labelled SHOULD_NOT_CHANGE) that is changing after a function call that is seemingly unrelated. My array is not global and the function call does not include the particular array. If anyone could figure out what is happening I would greatly appreciate it. Here is the main:
int main(){
int generate4[16] = {0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int propagate4[16] = {0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0};
int SHOULD_NOT_CHANGE[4] = {0, 1, 0, 0};
int carry_in16[4] = {1,2,1,1};
int carry_in4[16] = {0};
printf("\nShould be 1: %d", SHOULD_NOT_CHANGE[0]);
printf("\nShould be 0: %d", SHOULD_NOT_CHANGE[1]);
printf("\nSHOULD NOT CHANGE : ");
print_binary_array(SHOULD_NOT_CHANGE, 4);
// Here is where the problem is
carry(propagate4, generate4, carry_in4, carry_in16, 64, 4);
printf("\n\nShould be 0: %d", SHOULD_NOT_CHANGE[0]);
printf("\nShould be 1: %d", SHOULD_NOT_CHANGE[1]);
printf("\nSHOULD NOT CHANGE : ");
print_binary_array(SHOULD_NOT_CHANGE, 4);
return 0;
}
Here is the culprit function:
void carry(int* p, int* g, int* carry_in, int* group_carry, int size, int block)
{
for (int j = 0; j < block; j++){
carry_in[j] = g[j] + p[j] * group_carry[j];
for (int i = 1; i < block*4; i++){
carry_in[4*j+i] = g[4*j+i] + p[4*j+i] * group_carry[j];
}
}
}
And here is my output:
Should be 0: 0
Should be 1: 1
SHOULD NOT CHANGE : 0010
Should be 0: -13136
Should be 1: 0
SHOULD NOT CHANGE : 1-21471898220-13136
Upvotes: 0
Views: 37
Reputation: 24052
You are indexing past the bounds of carry_in
in function carry
. block
is 4, so 4*block
is 16. So j
runs from 0 to 3, and i
runs from 1 to 15. So 4*j+i
can be as large as 12+15 = 27, which is way larger than the maximum safe value of 15.
Upvotes: 1