sprintf访问冲突 [英] sprintf access violation

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

问题描述

我对以下代码有疑问:

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

它可以编译,但是当我运行它时,它给了我臭名昭著的 0XC0000005访问权限违反错误。我曾尝试将b设置为NULL,, 0,0和一堆其他东西,但随后出现 0XC0000005访问冲突错误或表达式:string!= 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天全站免登陆