user3229927 user3229927 - 3 months ago 17
C Question

Segmentation fault in my Vigenere encryption program

I'm new to programming. This is the code as I've written it so far. Disregard the details of the encryption itself; I know that will need more work. When I try to run the program, I get a segmentation fault error message. If

argc != 2
I will get the message and if
argc == 2
it prints out "keyword" but then it shows the same message and doesn't complete the program, so I think the error has something to do with referincing argv[1].

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

int main (int argc, string argv[])
{
int i = 0, n = strlen(argv[1]);
char KeyWord[i];

//makes sure command line has 2 arguements
if (2 != argc)

printf("argc != 2. Try again\n");
return 1;


//stores argv[1] as key
for (i = 0; i < n; i++)
{
KeyWord[i] = argv[1][i]; //malloc
printf("%c", KeyWord[i]);
}
printf("\n");

if (isalpha(KeyWord))
return 0;
else
{
printf("try again");
return 1;
}

int j, length;

printf("input data: ");
string message = GetString();

for (i = 0; i < n; i++)
{
for (j = 0, length = strlen(message); j < length; j++)
{
if (islower(message[j]))
message[j] = message[j] -97 + KeyWord[i];

if (isupper(message[j]))
message[j] = message[j] -65 + KeyWord[i];
}
if (i==n) i = 0;
}
}

Answer

You can't compute strlen(argv[1]) in the initialization of n before making sure that argc == 2.

Also, char KeyWord[i] is wrong: since i is 0, you are not allocating space for anything. This should at least yield a warning when you compile it, since array sizes must be greater than 0. If you want dynamic allocation, which your comment suggests, you should use malloc after computing the string's length.

The code should be:

int i = 0, n;
char *KeyWord; 

// make sure command line has 2 arguments
if (2 != argc) 
{
    printf("argc != 2. Try again\n");
    return 1;
}
n = strlen(argv[1]);
KeyWord = malloc(n+1);
/* ... */