-1

I am writing a program to just check what pointers do. But I get a segmentation fault(core dumped) message when I seem to have more than two pointers. I have checked for solutions online but the segmentation faults that are dealt with seem to be completely different to this problem.

#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;
}

But if I have just two pointers nothing seems to be wrong. Like if I comment out all the sections related to one pointer(except declaring and initializing) it seems to work fine.

Also I am using ubuntu 16.04(if it is somehow important).

Can anyone please explain why this is happening.

1 Answers1

3
  *p2=x;

As p2 is pointing NULL and you are trying store x value at NULL location

is causing problem


For debuging such crash gdb is your best friend.

copied your code in 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) 

So After OP's Update in Question, Update in Answer :)

int *p1, *p2, *p3;

  *p2=x;

So taking uninitialised pointer and dereferencing that pointer is Undefined behaviour. You should not do this.

You should assign p2 with some valid address of memory and then only you can write some value on tht pointer pointed address.

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222