0

I have seen related queries but that did not help https://gist.github.com/arshsherdill/174fe2945f3d43f3b33e1c307f7fde48

On running as ./vignere bacon. it shows segmentation fault i am unable to find what causes this error. Even debugging did not helped

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

int key_len;
//function to check that all characters in argv[1] are valid characters
int check(string c)
{
    key_len=strlen(c);
    for(int i=0;i<key_len;i++)
    {
        if(!isalpha(c[i]))
            return 1;
    }
    return 0;
}
//funvtion to change characters as done in caesar cipher
char caesar(char c,int k)
{
    if(isupper(c))
    return ((((c-'A')+k)%26)+'A');
    if(islower(c))
    return ((((c-'a')+k)%26)+'a');
    else 
    return 0;
}

int main(int argc, string argv[])
{
    string k="";
    if(argc==2)
    {
        if(check(argv[1])==1)
            return 1;

        for(int j=0;j<key_len;j++)
        {
            //I have stored values of key to be used later
            k[j] = tolower(argv[1][j])-'a';
        }
        //plaintext
        string p = GetString();
        int len_text = strlen(p);
        //ciphertext
        string c="";

        int l=0;//key index

        for(int r=0;r<len_text;r++)
        {
            if(isalpha(p[r])){
                //caesar shift function
                c[r]=caesar(p[r],k[l]);

            //key is used only when the p[r] is a character
                if(l<key_len-1){
                    l++;
                }
                else
                    l=0;

            }
            else
            {
                c[r]=p[r];

            }

        }
        printf("%s\n",c);
    }





    //if conditions are not met
    else
        return 1;
}

1 Answer 1

1

This string k=""; is the root of the seg fault. Declaring k a "string literal", in other words setting it in the declaration, makes it "read only", or constant. Therefore, it is immutable; it cannot be changed. It is technically this line k[j] = tolower(argv[1][j])-'a'; that gives the seg fault.

2
  • Thanks i did that again and now it is working gist.github.com/arshsherdill/a3a6a2e7daab01583b19cb60b3e0a500
    – 4rshdeep
    Dec 15, 2016 at 11:19
  • Don't forget to allocate a byte for the null-terminator in the malloc. In a small program like this, it may not cause an error ("unpredictable result"), but as you progress in the psets, memory management becomes much more important. And don't forget how we say "Thanks" on Stack Exchange. Dec 15, 2016 at 12:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .