0

I'm trying to solve the Caesar pset, and I think I'm mostly on the right way, but I just started getting the error "Segmentation fault (core dumped)". I've attached the code, hopefully someone can point out, what I did wrong.

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

char rotate(char c, int n);

int main(int argc, string argv[])
{
    // SAVE CLA AS VARIABLES
    string plaintext = get_string("plaintext: ");
    int key = atoi(argv[1]);
    string ciphertext = "";
    int length  = strlen(plaintext);

    for (int i = 0; i < length; i++)
    {
        ciphertext[i] = rotate(plaintext[i], key);
    }

    printf("%s\n", ciphertext);
}

char rotate(char c, int n)
{
    //test if c = key is in right range
    c = c + n;

    while (c > 122)
    {
        c = c - 122 + 64;
    }


    return c;
}

1 Answer 1

0

Your code shouldn't do:

string ciphertext = "";
int length  = strlen(plaintext);

Instead try:

int length = strlen(plaintext);
char ciphertext[length]; // you here create an array of size length

Remember that strings are arrays of chars, so its better practice to use chars than strings. The error appears because strings are literally references to arrays, so by creating a reference to nothing (""), you cannot then easily change the content writing in memory you aren't allowed to write.

1
  • to be more specific, arrays are immutable. That means that once created, their size cannot be increased. You can put fewer items in an array, but you can't increase their size.
    – Cliff B
    Commented Dec 12, 2022 at 1:28

You must log in to answer this question.

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