[英]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.