简体   繁体   English

argv中更改char值导致分割错误

[英]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]... 我正在尝试将字符串转换为其字母数字值,并且每次尝试显示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. 我环顾四周,很多答案都说它是由0除/取模而来的,但我根本不这样做。 I've commented and uncommented stuff and I saw that without the else statement, it works fine. 我已经评论和未评论的东西,我看到没有else语句,它就可以正常工作。 If the program works for the if statement, why should it give an error for the else statement?? 如果程序适用于if语句,为什么应该为else语句给出错误?

Your problem is the printf -statement. 您的问题是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. 问题在于, argv[1]仍然是char* ,因此所有值都被解释为字符,而不是整数。 These are not printable since they are in the range 0 - 26. You want to output them one by one as integers. 它们在0-26范围内,因此无法打印。您希望将它们一一输出为整数。

This also might explain an input-dependent segmentation fault if the output string has no valid end anymore, but I cannot reproduce that. 如果输出字符串不再具有有效的结尾,这也可能解释了与输入有关的分段错误,但是我无法重现该错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM