分段错误(核心转储)超过两个指针

时间:2016-11-03 06:25:56

标签: c pointers

我正在编写一个程序来检查指针的作用。 但是当我看起来有两个以上的指针时,我得到一个分段错误(核心转储)消息。我已经在线检查了解决方案,但处理的分段错误似乎与此问题完全不同。

#include<stdio.h>

int main()
{
  int x=3,y=3;
  int *p1, *p2, *p3;

   p1=&x;
  *p2=x;
   p3=&x;

  printf("%d\n",*p1);
  printf("%d\n",*p2);
  printf("%p\n",p1);
  printf("%p\n",p2);
  printf("%p\n",p3);



 return 0;
}

但如果我只有两个指针似乎没有错。 就像我注释掉与一个指针相关的所有部分(除了声明和初始化),它似乎工作正常。

我也在使用ubuntu 16.04(如果它有点重要)。

任何人都可以解释为什么会这样。

1 个答案:

答案 0 :(得分:3)

  *p2=x;

由于p2指向NULL并且您正在尝试将商店x值设置为NULL位置

导致问题

为了解决这种崩溃问题,gdb是你最好的朋友。

在test.c中复制了您的代码

jeegar@jeegarp:~$ gcc -g test.c 
jeegar@jeegarp:~$ ./a.out 
Segmentation fault (core dumped)
jeegar@jeegarp:~$ gdb ./a.out 
GNU gdb (Ubuntu 7.10-1ubuntu2) 7.10
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./a.out...done.
(gdb) r
Starting program: /home/jeegar/a.out 

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400612 in main () at test.c:10
10    *p2=x;
(gdb) 

在OP的问题更新后,答案更新:)

int *p1, *p2, *p3;

  *p2=x;

因此,使用未初始化的指针并取消引用该指针是未定义的行为。你不应该这样做。

您应该为p2分配一些有效的内存地址,然后只能在指针指向的地址上写一些值。