Home > Mobile >  C segmentation fault Pset2 Cs50
C segmentation fault Pset2 Cs50

Time:12-23

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]);
 }
}

CodePudding user response:

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.

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

CodePudding user response:

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.

  • Related