函数

时间:2016-08-10 11:00:28

标签: c function overflow

我是C编程的新手,而且我一直在编写一个从STDIN获取输入的虚拟计算机程序,输入基本上代表了让虚拟计算机执行一定数量检查的倍数的命令 - 只是简单的东西。基本上当我第一次编写这个程序时,我正在使用指向文件流的文件指针从文件中读取输入,但是当我将流程切换到STDIN时,它开始变得很奇怪。

这个STDIN的有趣之处在于它是一个文件流重定向,所以我仍然在命令行参数中提供一个文件,但是因为我使用的编码平台有一个允许文件重定向的命令,而不必实现一个实际的文件指针,让我感到困惑。

我开始遇到溢出错误,当我以前有命令行参数中提供的程序的文件指针时没有发生,我不知道为什么因为我刚刚将文件指针流切换到stdin`, 。如果有人可以向我指出问题可能是什么,我会非常感激,这是我从以下代码中获得溢出错误的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*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<100){

        checkWordFlow(*instructionCounter, memory);

        *instructionRegister=memory[*operand];  /*stores current instruction */

        *operand=memory[*instructionCounter]%100;   /* Stores the 2 right  digits  */

        checkSegmentationFault(operand);         /* checks that operand does not contain a negative value so that the problem does not throw a seg fault */

        *operationCode=memory[*instructionCounter]/100; /* Stores the 2 left diigts */

        if(*operationCode==10){ /*READ: inquires the user to provide input and stores it in specified address in the instructions*/

            scanf("%d",&memory[*operand]);

        }
        else if(*operationCode==11 ){ /*WRIT*: prints out the data in a memory element when executed*/
            printf("%d\n",memory[*operand]);
        }

        else if(*operationCode==12 ){ /*PRNT */

            while(1){   /*Loops and prints the followiing values that prnt passes in as operand */  

                /*Checks if the ASCI values are within the correct range */                
                if((memory[*operand]/100 > 65 &&memory[*operand]/100 <90)  || memory[*operand]/100 == 10 )
                    printf("%c",memory[*operand]/100);
                else if (memory[*operand]/100 == 0){
                    break;
                }
                else {
                    printf("Unknown Character\n");
                    exit(0);
                }
                if((memory[*operand]%100>65 &&memory[*operand]%100 <90)  || memory[*operand]%100 == 10)
                    printf("%c", memory[*operand]%100);
                else if (memory[*operand]%100 == 0){
                    break;
                }

                else{
                    printf("Unknown Character\n");
                    exit(0);
                }

                (*operand)++;  
            }
            *operand =0;  /*Resets the value of operand since it was incremented, so that it wont mess up the HALT print*/
            printf("\n");
        }
        else if(*operationCode==20 ){  /*LOAD : loads into the accumulator */
            *accumulator = memory[*operand];

        }
        else if(*operationCode== 21){  /*STORE: stores the accumlator value into the specific memory cell*/
            memory[*operand] = *accumulator;
        }

        else if(*operationCode==30 ){ /*ADD: adds into the accumulator the specificed memory address data*/
            *accumulator+=memory[*operand];
        }

        else if(*operationCode==31 ){ /*SUB: substracts from the accumulator the specified memoery addres data*/
            *accumulator= *accumulator - memory[*operand];
        }
        else if(*operationCode== 32){ /*DIV: divides from the accumulator the specificed memory address data */

            if(memory[*operand] >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){
        puts("You didn't specify the arguments or parameters\n");
        exit(0);

    }
    /*fill the buffer */
    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 < 0 || *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(instructionCounter<100){
        if(memory[instructionCounter]>9999)
        { printf("Word Overflow at memory element %d\n program will exit\n", instructionCounter);
            exit(0);
        }
        instructionCounter++;
    }
    return 1;
}

输入流看起来像这样:(就像我上面提到的,这个流被重定向到VIM命令,它欺骗程序从文件中读取而不必实际实现文件指针)

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

我已经摸不着头几个小时了,我无法弄清楚为什么会这样做,因为我说我是C编程的新手,我仍然不知道如何调试和做C的东西,我来自Java背景。

编辑1:用户没有将程序写入虚拟计算机,程序已经编写,用户只需通过VIM中的命令重定向STDIN,如(./computer < prog1)(./computer < prog2)。程序应该成功编译,然后当计算机确定它是什么类型的程序时,它将根据它的任务提示用户输入。所以它可以要求用户输入值,然后它会计算它们的平均值,如果那是重定向到它的程序。

1 个答案:

答案 0 :(得分:0)

如果您正在接收用户的输入,那么代码将会有所不同。

有几个选项,

  1. 保留相同的代码,但在用户输入所有数据后按Ctrl-Z。这只有在您是唯一输入数据的人时才有效,并且通常不可行。

  2. 每次循环后,您都可以询问用户是否要输入更多数据。然后,您可以将输入作为y/n获取,并在用户输入y时循环返回。

  3. 以下是一个例子。

    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. 循环固定的次数,但您的原始代码不能正常工作,这对您来说不是一个好选择。