【问题标题】:C - store to null pointer error, segmentation faultC - 存储到空指针错误,分段错误
【发布时间】:2017-07-26 05:34:29
【问题描述】:

请耐心等待我的代码。我是 C 的初学者。下面的代码构建了一个 Vigenere 密码。用户输入用于加密plaintext 消息的key 参数。代码将输出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);

}

【问题讨论】:

  • 您尝试取消引用空指针并写入它?这应该很清楚。如果你不知道指针,那你为什么要使用它们呢? Get a couple of good beginners books 并阅读。先学后用。
  • string y = NULL; --> string y = calloc(strlen(t)+1, sizeof(char));
  • 在不相关的注释上,请避免使用magic numbers。如果97 是指ASCII 字符'a',那么say 就是这样。或者更好的是,因为你想在大写和情人之间转换使用touppertolower。您已经使用了toupper,但错误的是,您应该改用isupper
  • 关于指针,类型名称stringchar * 的别名。它是一种指针类型。这是 CS50 及其库的坏处之一,它让您相信实际上您没有使用指针。虽然 CS50 库确实隐藏了 C 的一些复杂性,但这样做不利于在 IMO 中正确学习 C。
  • if (tolower(t[i])){ --> if (islower((unsigned char)t[i])){

标签: c pointers encryption segmentation-fault cs50


【解决方案1】:

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

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

当您执行y[i] 时,您取消引用了一个不允许的NULL 指针并导致错误。 NULL表示一个不存在的内存空间,所以你不能在这里存储你的密文!

要解决这个问题,你可以如下声明和初始化y

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

您必须#include &lt;stdlib.h&gt;才能使用calloc()功能。

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

在继续之前,您绝对应该了解指针以及内存的工作原理。某位程序员老兄在您原帖的 cmets 中发布了一个很棒的书单,看看吧!

【讨论】:

  • 谢谢!这真的很有帮助。
猜你喜欢
  • 2013-04-19
  • 1970-01-01
  • 2013-09-18
  • 2016-02-24
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 2012-04-10
  • 2021-04-10
相关资源
最近更新 更多