gpt4 book ai didi

c - 这个 _itoa_s 失败的技术原因是什么?

转载 作者:行者123 更新时间:2023-12-02 22:14:45 25 4
gpt4 key购买 nike

我正在尝试使用 _itoa_s 将数字的 0 到 9 转换为 ASCII,但我发现自己在使用 MSVC2012 时遇到堆栈损坏错误。

我以为ASCII表每个字符只占一个字节,但看起来,一个字节是不够的。

我的想法哪里错了?

for (int digit = 0; digit < 10; digit++)
{
char ch_digit;
_itoa_s(digit, &ch_digit, 1, 10);
}

我认为这个简单的循环应该会成功,但它失败了。我很困惑。

最佳答案

_itoa_s() 应该写出一个字符和终止 NUL 字符。您希望它写入长度 = 1 的缓冲区。因此,您要么因为未初始化的 ch_digit 而收到损坏错误,要么 _itoa_s() 不是 _s(安全)并且通过在那个字符后面写入来粉碎你的堆栈。

但为什么不直接“手动”计算以 10 为基数的 ASCII 字符,而不是使用这种不可移植的 MS 特定木材?

for (int digit = 0; digit < 10; digit++)
{
char ch_digit = '0' + digit; //'0' == 48 == 0x30
}

关于c - 这个 _itoa_s 失败的技术原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14673191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com