簡體   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