0

I am trying to write a simple encryption program (Caesar cipher) and I am running into a snag. I am relatively new to the world of C and pointers, coming from Java originally.

Whenever I run the following code, it will give me the error message Segmentation fault and terminate.

I have done a little reading about what that means, but I still don't fully understand it, or what is wrong with my code, or how to remedy the issue.

If you could help with any of those things that would be greatly appreciated.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

void encrypt(char *input);

int main()
{
    char *instructions = "pipi";

    encrypt(instructions);

    printf("Here are your secret instructions:\n%s\n", instructions);

    return (0);
}

void encrypt(char *input) {
    while (*input != '\0') {
        if (isalpha(*input)) {
            *input += 1;
            if (!isalpha(*input)) {
                *input -= 26;
            }
        }
        input++;
    }
}
SKD
  • 464
  • 1
  • 4
  • 16
Michael Ziluck
  • 599
  • 6
  • 19

1 Answers1

3

String literals in C, like "pipi" are read only, trying to modify such a string will lead to undefined behavior.

Use an array if you want to modify the string:

char instructions[] = "pipi";
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621