[英]Run-Time Check Failure #2 - Stack around the variable ''z" was corrupted
I have this code: 我有以下代码:
char z[9]; Int_To_BCD(vInt, z); Buflen += sprintf(BufStr + Buflen, "(%s)", z);
And: 和:
void Int_To_BCD (int val, char *out) {
void Int_To_BCD(int val,char * out){
int i = 0; int j = 0; int outIndex = 0; unsigned char digits[4]; unsigned char Digit[2]; memcpy((void*)digits, (void*)&val, 4); for (i = 0; i <= 3; i++) { Digit[0] = (digits[i] & HIGH) / 16; Digit[1] = digits[i] & LOW; for (j = 0; j < 2; j++) { sprintf(&(out[outIndex]), "%d", Digit[j]); outIndex++; } } if (outIndex == 0) { sprintf(&(out[outIndex]), "%d", 0); outIndex++; } out[outIndex] = '\\0'; }
In debug mode: the program run until the end of the main function and show the message: 在调试模式下:程序运行到主要功能结束并显示以下消息:
Run-Time Check Failure #2 - Stack around the variable 'z' was corrupted 运行时检查失败#2-变量'z'周围的堆栈已损坏
the maximun of outIndex is 8 always. outIndex的最大值始终为8。 and z has 8 bytes of memory.
z具有8个字节的内存。 hasn't it?
不是吗
What is the problem? 问题是什么?
Thanks! 谢谢!
Here you seem to take upper and lower half of the byte. 在这里,您似乎占用了字节的上半部分和下半部分。
Digit[0] = (digits[i] & HIGH) / 16;
Digit[1] = digits[i] & LOW;
These are hex digits: they range from 0-15. 这些是十六进制数字:范围是0-15。
This means that if the last digit is greater than 9, sprintf
with %d
will print 3 characters (2 digits and \\0
) and you will have a buffer overflow. 这意味着如果最后一位数字大于9,则带有
%d
sprintf
将打印3个字符(两位数字和\\0
),并且缓冲区溢出。
Use %c instead of %d in 在中使用%c代替%d
sprintf(&(out[outIndex]), "%d", Digit[j]);
is it working well? 运行良好吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.