Error de desbordamiento en la función.

Soy nuevo en la progtwigción de C y he estado escribiendo un progtwig de computadora virtual que toma entradas de STDIN, las entradas básicamente representan comandos que le piden a la computadora virtual que realice una verificación de múltiples de cierto número, solo cosas simples. Esencialmente, cuando escribí por primera vez este progtwig, estaba leyendo mi entrada de un archivo utilizando punteros de archivo que se dirigían directamente a las secuencias de archivos, pero luego, cuando cambié mi secuencia a STDIN, empezó a ponerse raro.

Lo interesante de este STDIN es que es una redirección de flujo de archivos, por lo que sigo proporcionando un archivo en el argumento de la línea de comandos, pero como uso una plataforma de encoding que tiene un comando que permite la redirección de archivos sin tener que implementar un puntero de archivo real, es confundiéndome

Comencé a recibir errores de desbordamiento que no ocurrían cuando solía tener punteros de archivo a los progtwigs que se proporcionan en el argumento de la línea de comandos, no tengo idea de por qué, como acabo de cambiar mi flujo de puntero de archivo a stdin` ,. Apreciaría enormemente si alguien pudiera señalarme cuál podría ser el problema, aquí está el código del que obtengo los errores de desbordamiento:

#include  #include  #include  /*Calling in the prototypes NOTE: I don't call execute/compile because they preceed the main method */ int printMemory(int* accumulator, int* instructionCounter, int* instructionRegister,int*operationCode,int* operand, int memory []); int checkSegmentationFault(int *operand); int checkWordFlow(int instructionCounter, int memory []); /* Function Name: compile Parameters: A pointer to the file that we are processing, the memory array, a pointer to instructionCounter, instructionRegister, operationCode, and operand, so that we can carry operations on them Return value(s): returns 1 if it compiles succesfully otherwise it would return a zero or terminate. Partners: None Description: This function reads in the file through it's pointer line by line and then converts it's data into 4 digit values, then they get stored into memory array. The function the proceeds to check for some compiling errors then it returns the result. */ int compile (FILE* fPointer , int memory [], int* instructionCounter , int* instructionRegister ,int*operationCode ,int* operand){ char s[80]; /* The buffer */ *instructionRegister=0; *operationCode=0; while(((*instructionRegister)=fscanf(fPointer,"%d %s %d", operationCode,s,operand)) != EOF){ /*Reads data line by line then stores the integer returned by fscanf to instructionRegister pointer so that I can check for formating */ if((*instructionRegister) ==3 ){ /*Checks for improper format by comparing the current instructionRegister count to 3, returns improper format otherwise */ if(*operand >9999|| *operand <0){ /* Checks for word overflow in compiler, makes sure that digits do not exceed 9999 */ printf("attempts to place a word in memory that is larger than 4 digits, or attempted to pass in a negative value\n "); exit(0); } /*Compares the string section of the code and checks if it matches the following words and then it converts it to it's 4 digit value by adding into it the operand */ if(strcmp(s,"READ") == 0) { memory[*operationCode] = 10 * 100 + *operand; } else if(strcmp(s,"WRIT") == 0) { memory [*operationCode] = 11 * 100 + *operand; } else if(strcmp(s,"LOAD") ==0){ memory [*operationCode] = 20 * 100 + *operand; } else if(strcmp(s,"PRNT") ==0){ memory [*operationCode] = 12 * 100 + *operand; } else if(strcmp(s,"STOR") ==0){ memory [*operationCode] = 21 * 100 + *operand; } else if(strcmp(s,"SET") ==0){ memory [*operationCode] = *operand; } else if(strcmp(s,"ADD") ==0){ memory [*operationCode] = 30 * 100 + *operand; } else if(strcmp(s,"SUB") ==0){ memory [*operationCode] = 31 * 100 + *operand; } else if(strcmp(s,"DIV") ==0){ memory [*operationCode] = 32 * 100 + *operand; } else if(strcmp(s,"MULT") ==0){ memory [*operationCode] = 33 * 100 + *operand; } else if(strcmp(s,"MOD") ==0){ memory [*operationCode] = 34 * 100 + *operand; } else if(strcmp(s,"BRAN") ==0){ memory [*operationCode] = 40 * 100 + *operand; } else if(strcmp(s,"BRNG") ==0){ memory [*operationCode] = 41 * 100 + *operand; } else if(strcmp(s,"BRZR") ==0){ memory [*operationCode] = 42 * 100 + *operand;; } else if(strcmp(s,"HALT")==0){ memory [*operationCode] =9999; } else { /* Prints back to the user that the compiler did not recognize one of them commands as it was going through it */ printf ("This is an unknown command, commands are case sensitive, program will now exit \n"); exit(0); } } else{ /* Returns improper format if instructionRegister does not match 3*/ printf("Improper Format, program will now exit \n"); exit(0); } } /* Checks if the instruction data contains a HALT, if not it would terminate */ while(*instructionCounter<100){ if (memory[*instructionCounter] == 9999){ return 1; } else (*instructionCounter)++; } printf("Halt was not found, program will now exit"); exit (0); } /* Function Name : execute Parameters : accumulator for storing in the arithematic operations , instructionCounter for counting the instructions, instructionRegisterfor storing the current instruction, operationCode stores the first 2 digits so that it would recognize what command is currently being executed, operand stores the next 2 digits , and the memory to be able to loop through the computer 100 memory Return value(s) : returns 1 if it executes fine, otherwise it would terminate if it finds an error. It also prints out HALT once found which shows the current state of the memory. Partners : None Description : This function processes the compiled instructions and start carrying out operations on them depending on their operation code, it also checks for error then it prints out the current memory state once it reaches HALT, */ int execute(int* accumulator , int* instructionCounter , int* instructionRegister ,int*operationCode ,int* operand, int memory []) { /* Resets the values to zero because they were used in the compiler */ *operand=0; *operationCode=0; *instructionRegister=0; *instructionCounter=0; *accumulator=0; /* this loop starts looking at the 4 digit memory cells and executes them 1 by 1 */ while(*instructionCounter 65 &&memory[*operand]/100 65 &&memory[*operand]%100 0){ /* Handles division by zero error */ *accumulator= *accumulator/memory[*operand]; } else { printf("Division by zero was attempted\n program will now exit \n"); exit(0); } } else if(*operationCode== 33){ /*MULT: multiplies to the accumulator the specified address data*/ *accumulator= *accumulator*memory[*operand]; } else if(*operationCode== 34){ /*MOD: calculates the remainder to the accumulator the specified address data*/ *accumulator= *accumulator%memory[*operand]; } else if(*operationCode ==40){ /*BRAN: jump memory execution to address given */ *instructionCounter= *operand; (*instructionCounter)--; /* deduct counter by 1 so that the loop does not skip over instructions */ } else if(*operationCode ==41){ /*BRNG: jumps memory execution to addres given only if accumulator is negative*/ if (*accumulator <0){ *instructionCounter=*operand; (*instructionCounter)--; /* deduct counter by 1 so that the loop does not skip over instructions */ } } else if(*operationCode ==42){ /*BRZR jumps memory execution to memory location only if accumulator is zero*/ if(*accumulator ==0){ *instructionCounter=*operand; (*instructionCounter)--; /* deduct counter by 1 so that the loop does not skip over instructions */ } } else if(*operationCode == 99){ /*HALT: terminates the program but prints out the memory state before it does that*/ printMemory(accumulator,instructionCounter,instructionRegister,operationCode,operand,memory); /*prints the memory out */ exit(0); } else if(*operationCode == 0){ /* Checks for empty elements and moves passt them */ (*instructionCounter)++; continue; } else{ /* Handles unrecognized operation codes */ printf("Unknown Command, program will now exit\n"); exit(0); } (*instructionCounter)++; /* Increment loop by 1 and start the next round of looping */ } return 1; } int main (int argc, char* argv[]){ FILE * fPointer=NULL; char fileName[150]; int accumulator=0; signed int instructionCounter=0; signed int instructionRegister=0; int operationCode=0; int operand=0; signed int memory [100]; /*Checks if the user passed in an argument at the command line*/ if(argc 1) strcpy(fileName,argv[1]); fPointer=stdin; /* If file failed to open then this would throw an error */ if(fPointer == NULL){ puts("File failed to open\n"); exit(0); } /* This loop fills the memory array with zeros*/ for(instructionCounter =0;instructionCounter<100;instructionCounter++){ memory [instructionCounter] = 0; } instructionCounter=0; /* Run the commands */ compile(fPointer, memory,&instructionCounter,&instructionRegister,&operationCode,&operand); execute(&accumulator,&instructionCounter,&instructionRegister,&operationCode,&operand,memory); return 1; } /* Function Name : printMemory Parameters : accumulator, instructionCounter, instructionRegister, operationCode, operand, memory array, to insure that we print out the correct state of the memory we have to pass them in Return value(s) : returns 1, but prints out memory state before it does that Partners : None Description : Prints out the current state of the memory in a nicely formatted manner */ int printMemory(int* accumulator , int* instructionCounter , int* instructionRegister ,int*operationCode ,int* operand, int memory []){ printf("REGISTERS:\naccumulator %+05d\ninstructionCounter %02d\ninstructionRegister %+05d\noperationCode %02d\noperand %02d\n", *accumulator, *instructionCounter, *instructionRegister, *operationCode, *operand); *instructionCounter =0; printf("MEMORY:\n 0 1 2 3 4 5 6 7 8 9\n"); for((*instructionCounter)=0;(*instructionCounter)<100;(*instructionCounter)+=10) /* loops through the memory array and outputs 10 elements in every row */ { printf("%2d",*instructionCounter); printf(" %+05d %+05d %+05d %+05d %+05d %+05d %+05d %+05d %+05d %+05d\n", memory[*instructionCounter], memory[*instructionCounter+1] , memory [*instructionCounter+2] , memory [*instructionCounter+3], memory[*instructionCounter+4], memory[*instructionCounter+5],memory[*instructionCounter+6],memory[*instructionCounter+7],memory[*instructionCounter+8],memory[*instructionCounter+9] ); } return 1; } /* Function Name : checksegmentationFault Parameters : operand. Return value(s) : returns 0, terminates the program if it tried to access an unknown operand , likely a negative value. Partners : None Description : terminates the program if it tried to access an unknown operand , likely a negative value., */ int checkSegmentationFault(int *operand) { if(*operand 100){ printf("SEGMENTATION FAULT: Attempted to access an unknown address \n"); exit(0); } return 0; } /* Function Name : checkWordFlow Parameters : instructionCounter for looping, and memory array Return value(s) : 1 , terminates if it reaches a word overflow Partners : None Description : this function checks for the word overflow possible error at execution by checking that digit values do no surpass 9999, */ int checkWordFlow( int instructionCounter, int memory []) /*fix this shit */ { instructionCounter=0; while(instructionCounter9999) { printf("Word Overflow at memory element %d\n program will exit\n", instructionCounter); exit(0); } instructionCounter++; } return 1; } 

El flujo de entrada se ve algo como esto: (Como mencioné anteriormente, este flujo se está redirigiendo con un comando VIM, engaña al progtwig para que lo lea de los archivos sin tener que implementar realmente los punteros del archivo)

 01 READ 60 02 LOAD 60 03 SUB 61 04 STOR 60 05 BRNG 15 06 READ 70 07 LOAD 70 08 ADD 80 09 STOR 80 10 LOAD 60 11 SUB 61 12 STOR 60 13 BRNG 15 14 BRAN 6 15 WRIT 80 16 HALT 99 61 SET 1 80 SET 0 

He estado rascándome la cabeza durante horas y no puedo entender por qué está haciendo eso, ya que dije que soy nuevo en la progtwigción de C y todavía no sé cómo depurar y hacer las cosas de C, vengo de Java fondo.

Edición 1: el usuario no escribe el progtwig en la computadora virtual, los progtwigs ya están escritos y el usuario simplemente redirige con STDIN mediante un comando en VIM como este (./computer < prog1) o (./computer < prog2) . El progtwig debe comstackrse con éxito, y luego, cuando la computadora descubra qué tipo de progtwig es, le pedirá al usuario que ingrese información dependiendo de su tarea. Entonces, podría pedirle al usuario que ingrese valores, luego calcularía su promedio si ese fuera el progtwig que se redirigió a él.

Si está tomando la entrada del usuario, entonces el código será diferente.

Hay algunas opciones,

  1. Mantenga el mismo código, pero ponga una condición en el usuario para presionar Ctrl-Z después de ingresar todos los datos. Esto solo funcionará si usted es la única persona que ingresa los datos, y generalmente no es viable.

  2. Después de cada ciclo, puede preguntar al usuario si desea ingresar más datos. Luego, puede obtener la entrada como y/n regresar si el usuario ingresa y .

A continuación se muestra un ejemplo.

 do { scanf("%d %79s %d",operationCode,s,operand)); // Other code here printf("\n Do you want to enter another value (y/n) "); scanf(" %c",&check); } while(check != 'n"); 
  1. Repita el ciclo por un número fijo de veces, pero su código original no funciona de esa manera y esta no será una buena opción para usted.