I have a function with the signature:
int exe(int stack[][STACKSIZE], int sp[], int reg[][REGISTERSIZE], int next_instruct[],
int next_inst[], int cur_proc, int *terminate);
It has the final two lines of:
printf("TWO cur_proc: %d\n",cur_proc);
return NORMAL;
And is called like this:
printf("ONE cur_proc: %d\n",cur_proc);
msg = exe(stack,sp,reg, next_instruct, next_instruct, cur_proc, &terminate);
printf("THREE cur_proc: %d\n",cur_proc);
And I am passing in cur_proc
which is considered a "read-only" (not that it should matter being passed by value) variable ins开发者_JAVA技巧ide of exe()
. Do my stuff inside of exe()
.
And my output is:
ONE cur_proc: 1
TWO cur_proc: 1
THREE cur_proc: -1
This is very confusing to me as I can't see any reason that this could possible be overwritten with a negative one.
What is a possible reason for this strange behavior?
You probably are writing outside the bounds of one of the arrays.
Inside the function, you are looking at a copy of the variable in the calling function, not at the original variable. Therefore, the printf()
inside the function does not tell you about when the value got corrupted in the calling function.
Look to the arrays that are passed, and the one that is modified inside the function is the most likely culprit - or the ones that are modified. Since none of the arrays are const-qualified, it is hard to say which are modified, but something is likely treading out of bounds.
If you want to track when the change to cur_proc
in the calling function occurs from inside the called function, pass a pointer to cur_proc
into the function - as well as or instead of the value - and print the value via the pointer.
If the code within your exe
function writes data to an invalid location in one of the arrays that are passed in, the stack could become corrupted which would potentially change the value of local variables higher up the stack (amongst other bad things).
Given the read-only nature of your variable from the functions perspective, either this is happening or another thread is modifying the value of cur_proc - the former seems more likely if you're not fiddling with threading.
Most debuggers allow you to place a breakpoint on "the changing of the value at a particular address in memory". If you get the address of cur_proc and break when the value at this address changes you should find your culprit.
精彩评论