简体   繁体   中英

C segmentation fault Pset2 Cs50

I am doing Pset2 cesear on CS50 and when i keep getting a segmentation fault when running the program. Why am i getting it and what is a segmentation fault. .................................................

#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(int argc, string argv[])
{
    string key = argv[argc-1];

    int keylen = strlen(key);

    string plaintext = get_string("Enter the plaintext: ");

    int ciphertext [strlen(plaintext)];

    int move[strlen(key)];

    int counter = 0;


    for (counter = 0; counter < 26; counter++)
    {
        if ((plaintext[counter] > 96) && (plaintext[counter] < 123))
        {
            move[counter] = (plaintext[counter]) - 97 ;
            ciphertext[counter] =key[move[counter]];
        }

        else if (plaintext[counter] > 64 && plaintext[counter] < 91)
        {
            move[counter] = plaintext[counter] - 65;
            ciphertext[counter] =key[move[counter]];
        }

        else ciphertext[counter] = plaintext[counter];
    }
 for (int loop = 0; loop < strlen(plaintext); loop++)
 {
 printf("%c\n", ciphertext[loop]);
 }
}

what is a segmentation fault.

A segmentation fault means: you tried to access memory which is not accessible to your program.

Why am i getting it

Because there is a bug in your program.

Without http://stackoverflow.com/help/mcve it's hard to tell where the bug is. Possibly it's in get_string() routine.

PS Never ever hide pointers behind typedef (as you apparently did for string ) -- this will only confuse you and other readers of your code.

If strlen(plaintext) is less than 26, then

for (counter = 0; counter < 26; counter++){
        if ((plaintext[counter] ...

is likely to cause a segfault as soon as counter >= strlen(plaintext) , since you are attempting to access the plaintext array outside of its bounds. You probably intended to iterate over the string rather than over the alphabet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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