C:使用 printf 时出现分段错误
这可能非常简单,但我似乎无法让它发挥作用。
我有这个非常简单的代码片段:
#include <stdio.h>
#include <string.h>
int main(void)
{
char buf[100];
char *p = buf;
strcpy(p, "Test string");
printf("%s\n", *p);
}
当我运行它时,它会导致分段错误。 GDB 输出:
Program received signal SIGSEGV, Segmentation fault.
0xb76af3b3 in strlen () from /lib/i686/cmov/libc.so.6
但我还是不明白。
评论将不胜感激,谢谢。
This one is probably very simple, but I can't seem to get it working.
I have this very simple snippet of code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char buf[100];
char *p = buf;
strcpy(p, "Test string");
printf("%s\n", *p);
}
Which causes a segmentation fault when I run it. GDB outputs:
Program received signal SIGSEGV, Segmentation fault.
0xb76af3b3 in strlen () from /lib/i686/cmov/libc.so.6
But I still don't get it.
Comments would be appreciated, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
当您写入时,
*p
将是p[0]
处的值,它是一个字符。然而 printf 正在寻找一个字符数组,从而导致它出现段错误。请记住,在 C 中,字符串只是字符数组,而数组实际上是指向第一个元素的指针,这就是为什么您不需要取消引用。要解决此问题,请删除 * 以获得:
When you write
the
*p
will be the value atp[0]
which is a character. The printf however is looking for an array of chars, thus causing it to segfault. Remember that in C, strings are just arrays of characters, and arrays are effectively pointers to the first element, this is why you don't need to dereference.To fix this remove the * to get:
您正在将一个字符传递给 printf;你应该传递指针。
You're passing a character to printf; you should be passing the pointer.
使用这个:
使用“p”而不是“*p”
Use this:
use "p" instead of "*p"
替换
为
当您使用
%s
时,printf 希望您传递char*
。您正在传递一个char
。Replace
with
When you use
%s
, printf expects you to pass achar*
. You are passing achar
instead.只需传递字符串(指针):
如果要打印第一个字符,则:
just pass the string(the pointer):
If you want to print the first char, then:
%s 导致 printf() 取消引用 *p。假设字符串是“测试字符串”。
然后在我的 Solaris sparc 机器上:(在测试程序中)p 将“瞄准”地址 0x54657374。该特定地址成为进程空间一部分的概率接近于零。
这就是导致 SIGSEGV 信号(段错误)的原因。
%s causes printf() to dereference *p. Suppose the string was "Test string".
Then on my Solaris sparc box: (in a test program) p would be "aimed at" the address 0x54657374. The probability of that particular address being part of your process space is next to zero.
That is what caused the SIGSEGV signal (segfault).