sprintf 访问冲突 [英] sprintf access violation

查看:30
本文介绍了sprintf 访问冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下代码有疑问:

for(i = 0;(i - 1)< n;i++)
{
char* b;
sprintf(b, "%d", i);
}

它编译得很好,但是当我运行它时,它给了我臭名昭著的0XC0000005 Access Violation"错误.我尝试将 b 设置为 NULL、"、0"、0 和一堆其他东西,但随后我收到0XC0000005 访问冲突"错误或表达式:字符串!= NULL.任何帮助将不胜感激!

It compiles fine but when I run it it give me the infamous "0XC0000005 Access Violation" error. I have tried setting b to NULL, "", "0", 0 and a bunch of other stuff but then I get the "0XC0000005 Access Violation" error or "Expression: string != NULL. Any help would be appreciated!

推荐答案

sprintf 将数据写入现有缓冲区,您将其作为第一个参数传入其中.目前,您根本没有为 b 指定值,这意味着(C 中的 IIRC)该值可以是任何值.如果将其设置为 NULL 或 0,sprintf 将尝试从地址 0 开始写入内存.

sprintf writes data into an existing buffer, which you pass into it as the first parameter. Currently you're not specifying a value for b at all, which means (IIRC in C) the value could be anything. If you set it to NULL or 0, sprintf is going to try to write into memory starting at address 0.

您需要创建一个适当大小的缓冲区,以便 sprintf 可以写入其中.例如:

You need to create a buffer of the appropriate size, so that sprintf can write into it. For example:

for(i = 0;(i - 1)< n;i++)
{
    char b[10];
    sprintf(b, "%d", i);
}

这是否是实际上你想如何分配缓冲区当然取决于你的真实代码想要对结果做什么.

Whether that's actually how you want to allocate the buffer depends on what your real code wants to do with the results, of course.

这篇关于sprintf 访问冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆