-1

I have written this caesar cipher program in c language,it runs fine until I provide the integer value for key but after that it crashes. can anyone please correct this code?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char alphabets[] = "abcdefghijklmnopqrstuvwxyz";
int arrow,key;
int search(char x)
{
    for(arrow=0;arrow<strlen(alphabets);arrow++)
    {

        if(x==alphabets[arrow])
        {
        return arrow;
        }
    }
}
char cipherGenerator(int arrow)
{
    arrow=arrow+key;
    if(arrow>strlen(alphabets))
    {
        arrow = (arrow%strlen(alphabets))-1;
    }
    return alphabets[arrow];
}

int main()
{
    char plain_text[]="",cipher_text[]="";
    int i;
    printf("Enter the plain text\n");
    gets(plain_text);
    printf("Enter the key\n");
    scanf("%d",&key);
    for(i=0;i<strlen(plain_text);i++)
    {
      strcat(cipher_text,cipherGenerator(search(plain_text[i])));
    }
    printf("The cipher text is %s:-",cipher_text);
    return 0;
}

1 Answers1

0

The crash can be explained by the attempt of writing into arrays of length 1.

char plain_text[]="",cipher_text[]=""; //these arrays have length 1

gets(plain_text); //will fail and crash here
strcat(cipher_text,cipherGenerator(search(plain_text[i]))); //will crash here

Regarding the usage of gets:

The gets() function does not perform bounds checking, therefore this function is extremely vulnerable to buffer-overflow attacks. It cannot be used safely (unless the program runs in an environment which restricts what can appear on stdin). For this reason, the function has been deprecated in the third corrigendum to the C99 standard and removed altogether in the C11 standard. fgets() and gets_s() are the recommended replacements.

Never use gets().

Community
  • 1
  • 1
P.W
  • 26,289
  • 6
  • 39
  • 76