user2985684
user2985684

Reputation: 1

segmentation fault from changing char value in argv

I'm trying to convert a string to its alphanumeric value and I get a Segmentation fault (core dumped) error every time I try to display argv[1]...

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


int main(int argc, char* argv[])
{        
    int key[strlen(argv[1])];
    for (int i=0,n=strlen(argv[1]);i<n;i++)
    {
        // i'm going to assume all command line arguments are alphabetic
        if(argv[1][i]<='Z')
            {argv[1][i]-='A';}
        else
            {argv[1][i]-='a';}

        key[i]=argv[1][i];
    }
    printf("%s",argv[1]);
}

I've looked around and a lot of answers have said that it came from dividing/modulo-ing by 0 but I don't do that at all. I've commented and uncommented stuff and I saw that without the else statement, it works fine. If the program works for the if statement, why should it give an error for the else statement??

Upvotes: 0

Views: 505

Answers (1)

user3072164
user3072164

Reputation:

Your problem is the printf-statement.

Do it like this:

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


int main(int argc, char* argv[])
{        
    int key[strlen(argv[1])];
    for (int i=0,n=strlen(argv[1]);i<n;i++)
    {
        // i'm going to assume all command line arguments are alphabetic
        if(argv[1][i]<='Z')
            {argv[1][i]-='A';}
        else
            {argv[1][i]-='a';}

        key[i]=argv[1][i];

        printf("%d ",argv[1][i]);
    }
}

The problem is, that argv[1] is still a char*, so all the values are interpreted as characters, not integers. These are not printable since they are in the range 0 - 26. You want to output them one by one as integers.

This also might explain an input-dependent segmentation fault if the output string has no valid end anymore, but I cannot reproduce that.

Upvotes: 1

Related Questions