csegmentation-faultcs50argvargc

I keep running into a segmentation error that I can't seem to be able to fix


For a course I'm taking I'm supposed to create a program that creates a simple ciphertext from plaintext using a key that the user inputs as a command line argument.

Here's the code, it's written in C

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

int main(int argc , string argv[])
{
    string key = argv[1];
    char keyL[2][26];
    char keyU[2][26];
    int normL = 97;
    int normU = 65;
    for (int i = 0;i <= 25;i++ , normL++, normU++)
    {
        keyL[0][i] = tolower(key[i]);
        keyU[0][i] = toupper(key[i]);
        keyL[1][i] = (char) normL;
        keyU[1][i] = (char) normU;
    }
    string plaint = get_string("plaintext:);
    string ciphert = "";
    int lengplain = strlen(plaint);
    for (int f = 0 ; f <= lengplain ; f++)
    {
        if (isupper(plaint[f]) == true)
        {
            for (int d = 0;d<=25;d++)
            {
                if (plaint[f] == keyU[0][d])
                {
                    ciphert[f] = keyL[1][d];
                }
            }
        }
        else if (islower(plaint[f]) == true)
        {
            for (int x = 0;x<=25;x++)
            {
                if (plaint[f] == keyU[0][x])
                {
                    ciphert[f] = keyL[1][x];
                }
            }
        }
        else
        {
            ciphert[f] = plaint [f];
        }
    }
    printf("ciphertext: %s\n" , ciphert);
}

This compiles but I run into a segmentation error when I run it. If you spot any logical errors please keep them to yourself. It's the segmentation error I am prioritizing to fix first.

Thanks!


Solution

  • Strings in c are not like strings in other languages. In c, strings are pointers to an array of characters in which the last character is the null terminator '\0'. When you declare the string ciphert = ""; you're essentially creating an length 1 array of characters with only the null terminator. The seg fault occurs when you try to access elements of ciphert that don't exist ciphert[f] = plaint[f]

    You'll have to declare ciphert as an array of length lengplain + 1 which makes it the same length as plaintext (plus the null terminator) and will allow you to do ciphert[f] = plaint[f]. I recommend you take a look at some guides on strings in c.