Home > Software engineering >  Segmentation fault (core dumped), cant figure why?
Segmentation fault (core dumped), cant figure why?

Time:05-03

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

int main(void)
{
    string cipher = "qwertyuiopasdfghjklzxcvbnm";
    string plaintext = "Hello World!";
    string ciphertext = "ciphertext: ";
    for(int j = 0; j < strlen(plaintext); j  )
    {
        if(isupper(plaintext[j]))
        {
            int k = plaintext[j] - 65;
            char append = toupper(cipher[k]);
            strncat(ciphertext, &append, 1);
        }
        else if(islower(plaintext[j]))
        {
            int l = plaintext[j] - 65;
            char append2 = tolower(cipher[l]);
            strncat(ciphertext, &append2, 1);
        }
        else
        {
            char append3 = plaintext[j];
            strncat(ciphertext, &append3, 1);
        }
    }
    printf("%s", ciphertext);
}

When running the above the error comes from trying to concatenate ciphertext and append. From what I can gather the error appears when trying to write to invalid memory location, I don't understand how this calls an invalid memory location?

CodePudding user response:

You declared a pointer to a string literal

string ciphertext = "ciphertext: ";

and then you are trying to change the string literal

strncat(ciphertext, &append, 1);

Any attempt to change a string literal results in undefined behavior.

You need to allocate a character array large enough to store concatenated strings as for example

char ciphertext[25] = "ciphertext: ";

Also in this if statement

    else if(islower(plaintext[j]))
    {
        int l = plaintext[j] - 65;
        char append2 = tolower(cipher[l]);
        //...  

there is incorrectly calculated an index in the string cipher. You should not use magic numbers like 65. At least use characters like 'a' or 'A'.

  • Related