简体   繁体   English

objective-c我无法理解为什么使用sprintf lead程序崩溃

[英]objective-c I can't understand why using of sprintf lead program to crash

-(void)InitWithPwd:(char *)pPwd
{

    char szResult[17];


    //generate md5 checksum
    CC_MD5(pPwd, strlen(pPwd),&szResult[0]);
    szResult[16] = 0;

    m_csPasswordHash[0]=0;


    for(int i = 0;i < 16;i++) 
    {

        char sz[3] = {'\0'};
        //crash in blow row. The first pass is ok. The third pass crash. 
        //I can't understand.
        sprintf(&sz[0],"%2.2x",szResult[i]);
        strcat(m_csPasswordHash,sz);
    }

    m_csPasswordHash[32] = 0;
    printf("pass:%s\n",m_csPasswordHash);
    m_ucPacketType = 1;

}

I want to get the md5 of the password. 我想得到密码的md5。 But above code crash again and again. 但上面的代码一次又一次崩溃。 I can't understand why. 我不明白为什么。

Your buffer ( sz ) is too small, causing sprintf() to generate a buffer overflow which leads to undefined behavior, in your case a crash. 您的缓冲区( sz )太小,导致sprintf()生成缓冲区溢出,导致未定义的行为,在您遇到崩溃的情况下。

Note that szResult[1] might be a negative value when viewed as an int (which happens when passing a char -type value to sprintf() ), which can cause sprintf() to disregard your field width and precision directives in order to format the full value. 请注意,当将szResult[1]视为int (在将char类型值传递给sprintf()时发生)时, szResult[1]可能是负值,这可能导致sprintf()忽略您的字段宽度和精度指令以便格式化全部价值。

Here is an example showing this problem . 这是一个显示此问题的示例 The example code is written in C, but that shouldn't matter for this case. 示例代码用C语言编写,但在这种情况下无关紧要。

This solves the problem by making sure the incoming data is considered unsigned: 这可以通过确保传入数据被视为无符号来解决问题:

sprintf(sz, "%02x", (unsigned char) szResult[i]);

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

相关问题 我不明白为什么 Objective-C 委托函数有效而 Swift 委托函数崩溃。 你能给我解释一下吗? - I don't understand why an Objective-C delegate function works and a Swift delegate function crash. Can you explain to me? 为什么我不能在 Objective-C 中切换枚举 - Why can't I switch an enum in Objective-C Objective-c代表不理解如何使用它们 - Objective-c Delegates can't understand how to use them Objective-C:子类化我不了解的东西 - Objective-C : Something that I don't understand with subclassing Objective-C:我对init方法不了解的东西 - Objective-C : Something that I don't understand with the init method 在Objective-C中不理解这种语法 - Don't understand this syntax in Objective-C Objective-C:为什么接口类型不能静态分配? - objective-C: Why interface type can't be statically allocated? Objective-C阻止“保留周期”警告,不明白为什么 - Objective-C block “retain cycle” warning, don't understand why 为什么在Objective-C中我不能在方法a()中调用方法b(),其中a和b在一个接口中 - Why in Objective-C I can't invoke method b() in method a(), where a and b are in one interface 为什么我不能在子类中使用超类的属性(Objective-C) - Why can't I use the property of a superclass in a subclass (Objective-C)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM