为什么会出现细分错误+如何消除它?

时间:2019-01-12 20:41:57

标签: c segmentation-fault coredump

我输入了这些代码+我遇到了细分错误。我正在尝试制作自己的特殊版本的strtol

struct optional_int {int Value; char IsNull;};
struct optional_int StrToHex(char Str[]) {
    const char Hex[0x10] = "0123456789ABCDEF";
    unsigned int Chr = 0x00,i,j,Number = 0x00;
    unsigned char IsNull, IsNegative;
    if(Str[0x0] == '-') {
        IsNegative = 0x1;
        int N_C_Char = 0;
        while( Str[N_C_Char]  !=  '\0' ) {
            Str[N_C_Char]=Str[N_C_Char+1];//right here
            N_C_Char++;
        }
    }else{IsNegative=0;}
    printf("%sfas", Str);
    for(i = strlen(Str); i > 0; i--){
        unsigned int Successes = 0x0;
        for( j = 0; j < 0x10; j++ ) {
            if( Str[Chr]==Hex[Chr]) {
                Number+=((pow(0x10, i))*j);
                Successes++;
            }
        }
        if(Successes!=1) {
            IsNull = 1;
        }else{
            IsNull = 0;
            Number = 0;
        }
        Chr++;
    }
    if(IsNegative == 1) {
        return (struct optional_int){ Number, IsNull};
    }else{
        return (struct optional_int){-Number, IsNull};
    }
}

int main(int argc, const char *argv[]) {
    printf("asdf %x\n", StrToHex("-535").Value);
}

每当我给它一个负数时,它就会给我一个分段故障核心转储,但我已经找到了问题。

1 个答案:

答案 0 :(得分:1)

好,所以我知道了。问题确实是您传递给函数的字符串。当您编写endpoint?.libInit(epConfig) // configure transport layer val transportConfig = TransportConfig() val pathToCerts = ctx.filesDir.absolutePath val certPath = "$pathToCerts/cl.pem" val caPath = "$pathToCerts/ch.pem" val keyPath = "$pathToCerts/p.key" transportConfig.tlsConfig.certFile = certPath transportConfig.tlsConfig.caListFile.plus(caPath) transportConfig.tlsConfig.privKeyFile = keyPath transportConfig.tlsConfig.verifyServer = true endpoint?.transportCreate(PJSIP_TRANSPORT_TCP, transportConfig) endpoint?.libStart() 时,该字符串已分配到程序的数据部分,因此您无法编写该字符串。当数字为负数时,您尝试通过将数字移到"-535"上来修改该字符串。这就是为什么它仅在负数时崩溃的原因。

-

此代码段在int main(int argc, const char *argv[]) { char c[200]; strcpy(c, "-535"); printf("asdf %x\n", StrToHex(c).Value); } 函数中对我有用。您将永远无法将常量字符串传递给引用此类字符串的函数或指针:

main

也会崩溃。

您必须提供一个具有写权限的存储位置。

解决该问题的另一种方法是不更改字符串以删除char c[200] = "-535"; StrToHex(c); ,而是编写代码以忽略它:)

相关问题