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;
}
CodePudding user response:
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:
- You attempt to write out of bounds of an array;
- 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.