So I've ran into this problem before and I was wondering if anyone could help me with it. It's really strange and I've never seen anything like it.
So I have this setup function which basically fills my global array of operation functions:
//A function Pointer is a type def that accepts two ints
fcnptr *opCode_Array; //Global Array of fcnptrs
void SetUp() {
int i;
fcnptr temp[41] = {NULL,movOP_1,mviOP_2,mifOP_3,mitOP_4,lriOP_5,ldrOP_6,strOP_7,mvrOP_8,addOP_9,addriOP_10,subOP_11,mulOP_12, divOP_13, orOP_14, andOP_15, notOP_16, bOP_17, beqOP_18, bneOP_19, bgtOP_20, bgeOP_21, bltOP_22, bleOP_23, pushdOP_24, pushrOP_25, pushiOP_26, popdOP_27, poprOP_28, putiOP_29, putsOP_30, lineOP_31, getiOP_32, getsOP_33, callOP_34, retOP_35, stopOP_36,addOP_9,addriOP_10,subOP_11,mulOP_12};
opCode_Array = (fcnptr*)malloc(41 * sizeof(fcnptr));
//fill global array with functions
for(i = 0; i < 41; i++) {
opCode_Array[i] = temp[i];
}
}
Later on I have a function that calls the operation functions like so:
void fetchExecute(int codeStoreLength) {
while(instructionPointer < codeStoreLength) {
//ip does not point to the instruction it is to execute during the loop, but the instruction that follows it.
instructionPointer += 3;
(*opCode_Array[codeStore[instructionPointer - 3]])(codeStore[instructionPointer - 2], codeStore[instructionPointer - 1]);
}
}
So normally this all works fine and dandy but last night and today I ran into some errors that caused segmentation faults when only calling specific functions, or more accurately, trying to access specific indexes of the opCode_Array.
If you noticed, I have two versions of the Addop, one at index 9 and another at index 37. When testing my function, I would get a segmentation fault when calling Addop at index 9 even when the code was completely commented out. I came up with a quick and dirty hack and just added another Addop to the end of the array and called addop from index 37 from now on. This worked completely fine and passed all the tests.
Now, another index is displaying the same behavior. It might be worth mentioning that this same index worked perfectly on previous tests. This has happened to a couple of my functions so I would rather just figure out why it's doing this than just move indexes around forever.
So far, I've tried p;laying around with pointers and making opCode_Array static but neither have helped..
Edit: Thank you everyone for the tips and help. I wasn't able to find the root of the problem but I was able to fix it by making the array local to fetchexecute instead of global. I would post more code but this is a school project that gets reused every year..
Lessons Learned? Don't make globals unless you have too I guess....