1

First off, I will show my code:

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Wrong command line arguments\n");
        return 1;
    }
    else
    {
        string plaintext = get_string("plaintext: ");
        string result = caesar_cipher((int) argv[1], plaintext);
        printf("ciphertext: %s", result);
        return 0;
    }
}

void append(string s, char c) {
        int len = strlen(s);
        s[len+1] = '\0';
        s[len] = c;
}

So, the code compiles correctly. But after entering plaintext, a segmentation fault error will appear. I have ran debug50 to try to detect the error and it seems to be in the append function in s[len]. However, I am not able to see what is wrong.

2

You can't do what you're trying to do here, at least not like this. Unlike other languages, strings (aka, char arrays) are immutable in C. That means that once they're created, their length cannot be changed.

This code is attempting to lengthen a string. When it tries to access memory beyond the end of the string, it's triggering a seg fault. The code would need to create a new string that is longer and then copy the content of the original string to do this.

Wouldn't it be much simpler to just create a result string for the encoded data that's the same length as the input string?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .