I am trying to build a basic Ceaser cipher of cryptography. The code which I have written is working in vscode of Windows but the exact same code is giving me error in vscode of Ubuntu. More particularly I am getting Segmentation fault error when I try to run the code in vscode of Ubuntu OS.
Code :
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char * Encrypted(char ** input, int key){
printf("%s\n", *input);
int length = strlen(*input);
printf("Length is %d ", length);
char * curr = *input;
char * encrypt = malloc(length);
strcpy(encrypt, "");
for(int i=0; i < length; i ){
int current = (int)curr[i];
char currentDecrypted = (char)(65 (current key - 65)&);
strncat(encrypt, ¤tDecrypted, 1);
}
return encrypt;
}
int main(void){
char * input;
printf("Enter the text to be encrypted : ");
gets(input);
// puts(input);
int key;
printf("Enter the key : ");
scanf("%d", &key);
printf("The encrypted text is : %s\n", Encrypted(&input, key));
}
Where exactly am I making a mistake.? Thanks in advance for the solution.
CodePudding user response:
The statement:
char * input;
declares a pointer to char
, or a char *
, but does not allocate any memory for it. The pointer is indeterminate, and dereferencing an indeterminate pointer invokes undefined behaviour.
From C11:
The behaviour is undefined in the following circumstances: ....
- The value of an object with automatic storage duration is used while it is indeterminate (6.2.4, 6.7.9, 6.8)
Then, the calls to gets
and printf
try to access memory they have no business accessing, and the call to strlen
tries to determine the length of a string in unallocated memory.
Aside:
gets(input)
gets
does no error-checking, is inherently dangerous and shouldn't be used. It has been removed from the C standard. Consider using fgets
instead.