I have been trying to do cs50's course (this course was my first introduction to c ever, please have mercy) and got to the substitution problem. I have been stuck on it for a while now. this is my buggy code:
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int check(string str);
int main(int argc, string argv[])
{
if(argc < 1 || argc > 2)
{
printf("Usage: ./substitution key");
return 1;
}
string key = argv[1];
if(check(key) == 1)
{
return 1;
}
string plaintext = get_string("plaintext:");
int lenght = strlen(plaintext);
char ciphertext[lenght + 1];
for(int i = 0; i <= lenght; i++)
{
if(islower(plaintext[i]))
{
plaintext[i] -= 97;
ciphertext[i] = key[(int)plaintext[i]];
if(isupper(ciphertext[i]))
{
ciphertext[i] = tolower(ciphertext[i]);
}
}
if(isupper(plaintext[i]))
{
plaintext[i] -= 65;
ciphertext[i] = key[(int)plaintext[i]];
if(islower(ciphertext[i]))
{
ciphertext[i] = toupper(ciphertext[i]);
}
}
}
printf("ciphertext:%s", ciphertext);
}
int check(string str)
{
//controlle del numero di lettere, che i caratteri della chiave non siano ripetuti o numerici hahahahah lol
char alphabet[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int count[26] = { 0 };
if(strlen(str) != 26)
{
printf("Key must contain 26 characters.");
return 1;
}
for(int i = 0; i < 25; i++)
{
if(isalpha(str[i]) == 0)
{
return 1;
}
str[i] = (char)tolower(str[i]);
for(int j = 0; j < 25; j++)
{
if(str[i] == alphabet[j])
{
count[j] += 1;
}
}
}
for(int i = 0; i < 25; )
{
if(count[i] != 1)
{
return 1;
}
}
return 0;
}
the main issue is that it seems impossible to handle argv[1] as a string by storing it, because whenever I run the program it just keeps running endlessly.
This is the segmentation error i get on the debug console:
Program received signal SIGSEGV, Segmentation fault. __strlen_evex () at ../sysdeps/x86_64/multiarch/strlen-evex.S:77
When I try to debug it says a segmentation fault has occured when trying to get the key lenght with strlen(). also when debugging and it says that key has stored 0x0, so maybe I somehow got wrong the assigning of argv[1] to key as well. I think it could be that argv[1] doesn't end with a
NULL character but I'm not sure as I only know the basics of c.