sprintf 访问冲突
我对以下代码有问题:
for(i = 0;(i - 1)< n;i++)
{
char* b;
sprintf(b, "%d", i);
}
它编译得很好,但是当我运行它时,它给出了臭名昭著的“0XC0000005 访问冲突”错误。 我尝试将 b 设置为 NULL、“”、“0”、0 和一堆其他内容,但随后收到“0XC0000005 访问冲突”错误或“表达式:字符串!= NULL”。任何帮助将不胜感激!
I have a problem with the following code:
for(i = 0;(i - 1)< n;i++)
{
char* b;
sprintf(b, "%d", i);
}
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
sprintf
将数据写入现有缓冲区,并将其作为第一个参数传递给它。 目前,您根本没有为 b 指定值,这意味着(C 中的 IIRC)该值可以是任何值。 如果将其设置为 NULL 或 0,sprintf
将尝试从地址 0 开始写入内存。您需要创建一个适当大小的缓冲区,以便 sprintf 可以写入其中。 例如:
当然,这是否实际上是您想要分配缓冲区的方式取决于您的实际代码想要对结果执行什么操作。
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.You need to create a buffer of the appropriate size, so that sprintf can write into it. For example:
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.
嗯...您指向 b 的指针包含垃圾,因为您尚未初始化它或分配空间。
Springtf 要求您分配一个目标缓冲区空间...
至少,您需要 char b[50] 或您期望的任何最大大小,而不仅仅是 char* 。
Umm... Your pointer to b contains garbage since you haven't initialized it or allocated space.
Springtf requires you to have allocated a destination buffer space...
At a minimum, you want something like char b[50] or whatever maximal size you expect, not just a char*.
char* 是指向 char 或 char 数组的未初始化指针。 需要定义一个缓冲区char[10],否则sprintf的目标地址未定义。
A char* is an uninitialized pointer to a char or char array. You need to define a buffer char[10], otherwise the target address of sprintf is undefined.
sprintf 需要向其传递一个已分配的字符缓冲区,该缓冲区足够大以存储任何可能的结果。 这很容易发生缓冲区溢出 - 您可能想使用更安全的 snprintf 来代替。 一种低效但安全的方法:
sprintf requires to pass it an already allocated character buffer large enough to store any possible result. This is highly subject to buffer overflows - you probably want to use the safer snprintf instead. One inefficient but safe way to do that:
非常感谢! 由于我需要一个 char* 我将代码重写为:
它的工作原理就像一个魅力。 我现在终于可以继续我的生活了! 再次非常非常感谢你们!
Thank you very much! Since I needed a char* I rewrote the code to:
and it works like a charm. I can finally now get on with my life! Once again thank you very very much!