开发者

Cannot reproduce error in debugger

I'm working on a research project in C, using Eclipse with the CDT, MinGW and GDB on Windows.

I have an int array with elements that should be between 0 and 3 (inclusive). I'm iterating through the array and switching on the number. I stuck an assert(0) in my default case in case I messed up somewhere and a number outside my bounds snuck in. Now, this assert is going off for certain input whenever I run my program. Fine - I messed up somewhere and an out-of-bounds number is sneaking in. That's something I can handle. The problem is, when I run the program in the debugger, everything works fine. The assert never fires, the results come out correct, and there's no problem. I'm less concerned over the fact that there is an error than the fact that I can't reproduce the error while debugging.

Here's the relevant code. Every %3 = 0 element of int* zeroPairs is (supposed to be) between 0 and 3 (inclusive). The next two elements are indexes into a different array and could be various numbers. j*3 will not go out of bounds of zeroPairs. The arrays A, B, C and D only contain 1 or -1 in each index. When I had a typical A = temp, A = B etc swap, it worked fine. When I simplified it to just changing the sign on each 1 is when this error started.

Thanks for helping!

for (j = 0; j < bits; ++j) {
        if (k & (1 << j)) { //Check if a bit is set, if so, swap the correct elements
            switch (zeroPairs[j * 3]) {
            case 0:
              开发者_如何学C  A[zeroPairs[j * 3 + 1]] = -A[zeroPairs[j * 3 + 1]];
                A[zeroPairs[j * 3 + 2]] = -A[zeroPairs[j * 3 + 2]];
                break;
            case 1:
                B[zeroPairs[j * 3 + 1]] = -B[zeroPairs[j * 3 + 1]];
                B[zeroPairs[j * 3 + 2]] = -B[zeroPairs[j * 3 + 2]];
                break;
            case 2:
                C[zeroPairs[j * 3 + 1]] = -C[zeroPairs[j * 3 + 1]];
                C[zeroPairs[j * 3 + 2]] = -C[zeroPairs[j * 3 + 2]];
                break;
            case 3:
                D[zeroPairs[j * 3 + 1]] = -D[zeroPairs[j * 3 + 1]];
                D[zeroPairs[j * 3 + 2]] = -D[zeroPairs[j * 3 + 2]];
                break;
            default:
                printf("Whoops %d", zeroPairs[j * 3]);
                fflush(stdin);
                assert(0);
            }

        }
    }


Debug builds often work "correctly" because uninitialized variables are set to their default.

Also, out of bound array and pointer access often do not cause an overwrite of other variables as there is extra padding between the elements. You still have a bug in debug build but you might not realise it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜