Working on my assignment, more details in another question. If I use
arr[(i * 16) % arrLen] *= 2; // seg fault
vs
arr[i % arrLen] *= 2; // OK!
Why? Full source see line 31. Why? I modulus the array length so it should be OK?
Working on my assignment, more details in another question. If I use
arr[(i * 16) % arrLen] *= 2; // seg fault
vs
arr[i % arrLen] *= 2; // OK!
Why? Full source see line 31. Why? I modulus the array length so it should be OK?
i * 16 can overflow into the negative range of signed integers. When you take modulo of a negative integer, you can get a negative remainder and that'll make your array subscript negative and result in an access outside of the array's allocated memory and sometimes a crash.
Assuming the size of an int on your system is 32-bits, chances are you're causing an overflow and the result of i * 16 is becoming negative. In a two's complement system, negative values are represented with a higher binary value.
int reps = 256 * 1024 * 1024;
So reps = 268,435,456, which is the value you're looping up until. The greatest value of i is therefore 268,435,455 and 268,435,455 * 16 = 4,294,967,280.
The largest positive value a 32-bit int can represent is 2,147,483,647 (4,294,967,295 for an unsigned int, so you haven't wrapped around the negatives yet), which means that result is being interpreted as a negative value.
Accessing a negative offset from arr is out of the bounds of your allocated memory, which causes undefined behaviour and fortunately a seg fault.
Looking at your full source:
memset(arr,0,arrLen);malloc(arrLen * sizeof(int)) however arrLen is created with a /sizeof(int), so you're canceling your work there...Regarding your seg fault, as others have stated your overflowing your array. You've created an array of ints. The then you're looping from 0 to reps (268,435,456) which is the max size of an int. When you try to multiply that by 16 you're overflowing and creating a negative offset.
Try multiplying the 16 into the initialization of reps:
int reps = 256 * 1024 * 1024 * 16;
Your compiler should throw a warning letting you know this exact thing:
warning: integer overflow in expression [-Woverflow]