获取分段错误(核心转储)

时间:2015-10-05 03:45:47

标签: c encryption

我的程序必须加密/解密文本文件,但是当我这样做时我得到segmentation fault(core dumped)

./program 9999 input.txt output.txt

程序从input文件中获取每个字符,并根据传递的key对其进行转换。当我在CodeBlocks中编译时它编译得很好并且没有给出任何错误。可以smb告诉我代码有什么问题吗?谢谢!

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


//Checks if the input arguments are less than 2 (starting from 0)
//A user should enter 3 arguments so as not to reach this method
int badProgram(const char *const program){
    printf("The program is missing some of the files!");
    return -1;
}

//Encrypts the passed inputFile and
//Produces its output to the passed outputFile
//Key is also passed as the seeding number
int encryptFile(FILE *input, FILE *output){
    char c;
    char p;
    int r = 0;
    char p1 = 0;
    char c1 = 0;

    while((p = fgetc(input)) != EOF){
        r = rand() % 97;
        //change all displayable characters [0...96]
        if(p == 't'){
            p1 = 0;
        }
        else if(p == '\n'){
            p1 = 1;
        }
        else{
            p1 = p - 30;
        }

        c1 = p1 ^ r;//bitwise xor
        if(c1 == 0){
            c = 't';
        }
        else if(c1 == 1){
            c = '\n';
        }
        else{
            c = c1 + 30;
        }
        //Write
        fprintf(output, "%c", c);
    }

}

int main(int argc, char *argv[])
{
    //Check the number of the entered arguments
    if(argc < 2){
        return badProgram(argv[0]);
    }
    else{
        FILE *input;
        FILE *output;

        //Seed a number into Random Generator
        int key = *argv[0];
        srand(key);
        input = fopen(argv[1], "r");
        output = fopen(argv[2], "w");
        encryptFile(input, output);

    }

    return 0;
}

**input.txt**看起来像这样:

Hello, World!

Bye!

1 个答案:

答案 0 :(得分:3)

您的代码出现了一些问题:

  • int key = *argv[0];很可能没有按照您的想法行事。 实际的作用如下:

      

    [0]参数(程序名称)的第一个字符的ASCII值分配给int变量
      您打算在那里做的很可能是:

    int key = atoi(argv[1]); // this converts "9999" into an int 9999

  • input = fopen(argv[1], "r");打开一个名为(在您的情况下)&#34; 9999&#34;阅读和失败。您从不检查错误,因此当您尝试使用input FILE指针时,这会导致崩溃。解决方法是使用argv[2]

  • 同样,您应该使用argv[3]作为输出文件
  • 您的encryptFile函数必须返回声明int的值(不知道为什么要从中返回值,因为您从未使用过它)

解决上述问题后,您的程序不再崩溃

更新

对上述问题和一般信息的一些解释:

  • argv将所有输入参数列为字符串(char*),其中第一个([0])参数是可执行文件名并且不是您的第一个论证&#34;&#34;程序名称
  • 应该始终检查文件操作的结果,因为它们很可能在&#34; normal&#34;程序运作
  • C / C ++没有自动&#34;将字符串转换为int(或double,但是提供了一整套函数来处理数字&#39;解析。这些功能的一些例子是:&#39; atoi&#39;,&#39; atol&#39;,&#39; atof&#39;
相关问题