Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Segmentation fault (core dumped) when trying to solve problem set

I’m trying to solve the Caesar pset in the Harvard CS50 course, and I think I’m mostly on the right way, but I just started getting the error "Segmentation fault (core dumped)".

Im still super new to coding, which is why i was having a bit of trouble figuring out the problem, when I was looking at other similar questions. Maybe someone could have a glance at my code and help.

#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 cipher = "";
    int length  = strlen(plaintext);

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

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First you have to remember that string is an alias for char *. That is, string is a pointer to a char.

Then for the problem: The definition

string cipher = "";

makes the variable cipher point to an empty string literal. More specifically it makes cipher point to the first element of an array, s all literal strings are really arrays of character. It’s an array of only a single element, which is the string terminator character '\0'.

Like any other array, its size is fixed and can not be made larger.

Unlike other arrays, literal string arrays are not allowed to be modified.

So you have two errors in your code:

  1. You attempt to write out of bounds of an array;
  2. And you attempt to modify a read-only literal string

Both of these errors leads to undefined behavior, which is a common cause of crashes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading