C - 存储为空指针错误,分段错误

时间:2017-07-26 05:34:30

标签: c pointers encryption segmentation-fault cs50

请耐心等待我的代码。我是C的初学者。下面的代码构建了一个Vigenere密码。用户输入key参数,用于加密plaintext消息。代码将输出ciphertext

我收到的错误如下。请注意,我还没有学过指针。

非常感谢任何诊断错误的帮助!

vigenere.c:47:13: runtime error: store to null pointer of type 'char'
Segmentation fault

代码

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(int argc, string argv[]){

// check for 2 arguments
if (argc != 2){

    printf("missing command-line argument\n");
    return 1;

} 

// check for character argument
int i,n;

for (i = 0, n = strlen(argv[1]); i < n; i++){

    if (!isalpha(argv[1][i])){

        printf("non-character argument\n");
        return 1;

    }

}

// if previous 2 checks are cleared, request 'plaintext' from user

printf("plaintext:");

// declare plaintext, key, and ciphertext

string t = get_string();    // plaintext
string u = argv[1];         // key (argument)
string y = NULL;            // ciphertext

// encode plaintext with key -> ciphertext

for (i = 0, n = strlen(t); i < n; i++){

    if (tolower(t[i])){

        y[i] = (char)((((int)t[i] + (int)tolower(u[i%n])) - 97) % 26) + 97;

    } else {

        y[i] = (char)((((int)t[i] + (int)tolower(u[i%n])) - 65) % 26) + 65;

    }


}


printf("ciphertext: %s\n", y);

}

1 个答案:

答案 0 :(得分:1)

您收到此错误消息,因为变量yNULL

类型string实际上是typedef(换句话说是别名)到char *,这意味着“指向char”,因此y是指针到char。

当您执行y[i]时,您取消引用不允许的NULL指针并导致错误。 NULL表示不存在的内存空间,因此您无法在此处存储密文!

要解决此问题,您可以按如下方式声明和初始化y

char *y = calloc(strlen(t) + 1, sizeof(char)); // Ciphertext, ready to hold some data !

您必须#include <stdlib.h>才能使用calloc()功能。

现在,y是指向与t一样大的内存空间的指针(明文和密文具有相同的大小),您可以取消引用并将数据写入!

在继续前进之前,你一定要学习指针以及内存是如何工作的。一些程序员老兄在您原帖的评论中发布了一个很棒的书籍列表,看看吧!