繁体   English   中英

C - 运行我的程序时出现分段错误(核心转储)错误

[英]C - Segmentation fault (core dumped) error when running my program

为了在 c 中练习,在我的caesar.c程序中,我使用我的 encrypt_text 方法来加密给定的文本(提示用户)。 我使用的是凯撒密码 function 作为密钥,我使用的是argv[1]元素(以 int 形式转换)。

在第一个 if 语句中,我检查运行程序时,用户仅键入一个元素(在程序名称之后),该元素不是零并且仅由数字组成(通过辅助方法checkString )。 如果满足条件,系统会提示用户输入要加密的文本。 否则,系统会要求用户再次运行该程序,并显示以下消息: Usage:./caesar Key

所以,一切似乎都正常工作,但是,当我运行程序时只输入程序名称(所以,基本上,只用一个元素填充 argv[] 数组),我遇到了分段错误(核心转储)错误。

因此,如果我使用命令./caesar 3运行程序,一切正常,但如果我使用命令./caesar (后面没有数字)运行程序,则会发生分段错误。

基本上,在最后一种情况下,我也需要返回相同的Usage:./caesar Key消息。

我读了很多关于这种与尝试访问不允许的 memory 有关的问题,但目前,我没有找到在我的特定程序中发生的原因。

一些建议?

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

void encrypt_text (string text, const int tlen, int shift, char* cipher);//encrypt method
int checkString(string strToCheck);

int main(int argc, string argv[])
{
    int key = atoi(argv[1]);//cast argv[1] to an integer

    if ((argc == 2) && (key != 0) && checkString(argv[1]) == 1)
    {

        //include cypher method
        string text = get_string("Text to cypher: ");
        int tlen = strlen(text);
        char cipher[tlen +1]; cipher[tlen] ='\0';
        int shift = key; // key

        //printf ("Text :\t\t%s\n", text);
        encrypt_text (text, tlen, shift, cipher);
        printf ("ciphertext:%s\n", cipher);
        text[0] = '\0';
        return 0;

    } else {
        printf("Usage: ./caesar Key \n");
         return 1;
    }
}


//encrypting method
void encrypt_text (string text, const int tlen, int shift, char* cipher) {
    char lower[] = "abcdefghijklmnopqrstuvwxyz";
    char upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    shift %= 26; // more than 26 make cycle[s]
    for (int ti=0; ti < tlen; ++ti) {
        if (islower (text[ti]))
            cipher[ti] = lower[(text[ti] - 'a' + shift) % 26];
        else if (isupper (text[ti]))
            cipher[ti] = upper[(text[ti] - 'A' + shift) % 26];
        else
            cipher[ti] = text[ti];
    }
}


//helper method for checking only digits strings
int checkString(string strToCheck) {

      for (int i = 0, n = strlen(strToCheck); i < n; i++) {
          int test = isdigit(strToCheck[i]);

          if (test == 0) {
              return 0;//found a non digit
              break;
          }
      }
return 1;//string has only digit
}

当您的程序在没有 arguments 的情况下执行时, argv[1]将没有关于 arguments 的任何信息NULL在某些环境中被放在那里。

因此,在这种情况下您不能执行atoi(argv[1])

检查应添加到声明中

int key = atoi(argv[1]);

喜欢

int key = 0;
if (argv >= 2) {
    key = atoi(argv[1]);
}

或(如果允许使用三元运算符):

int key = argv >= 2 ? atoi(argv[1]) : 0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM