'Why am I getting segmentation error in a Caesar cipher program?
I'm trying to write a program that uses Caesar's algorithm to cipher a string input. I'm a beginner to C but I can understand basic codes. So to cipher the text I wrote this code, but when I enter the input, I get an error that says
Segmentation fault (core dumped)
I tried to do some debugging by removing the else condition at the end and the program kind of worked for short inputs of 2-3 letters
Can someone please help me with this issue?
I'm using the CS50's header only to get the string in the first place.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
    char name[] = "";
    strcat(name, argv[1]);
    int key = atoi(name);
    string plaintext = get_string("plaintext: ");
    int length = strlen(plaintext);
    char ciphertext[] = "";
    for(int i = 0; i < length; i++)
    {
        int skipCount = 0;
        if(isalpha(plaintext[i]))
        {
            while(skipCount < key)
            {
                char tmp = (char) ((int) plaintext[i] + 1);
                if(isalpha(tmp))
                {
                    ciphertext[i] = tmp;
                    skipCount++;
                }
                else
                {
                    if (isupper(plaintext[i]))
                    {
                        tmp = 'A';
                        skipCount++;
                    }
                    if (islower(plaintext[i]))
                    {
                        tmp = 'a';
                        skipCount++;
                    }
                }
            }
        }
        else ciphertext[i] = plaintext[i];
    }
    printf("%s\n", ciphertext);
}
Solution 1:[1]
What you need to understand about C, is that it does not automatically allocate memory.
You have to it your self!
This line:
char name[] = "";
creates an array of size 1, which holds a single character - the "null" character = '\0';
It signifies an empty string.
You can not copy any larger string in to it, because all strings in C must have a null character at the end, so there isn't enough room for even a single readable character.
As a beginner, you would need to decide what the maximum length of the string you want will be, and declare the array to be of proper size:
char name[255];
This is one example that can hold up to 254 characters, plus the terminating null character.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | 
