Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   sigmentation fault (http://www.go4expert.com/forums/sigmentation-fault-t19149/)

inspire 24Aug2009 22:21

sigmentation fault
 
For the following code, I receive sig fault. Why? Thanks.
Code:

void test(int *i) {
  *i = 3; /* where the sig fault occurs */
}

int main() {
  int *p;
  test(p);
}

BTW, I'm using gcc 4.3.3 on Ubuntu 9.04.

c_user 25Aug2009 00:26

Re: sigmentation fault
 
see friend as per my logic u cannot assign a no. to a pointer so its showing u the fault....
>>*i=3 is the wrong statement....
hav a gud day...

inspire 25Aug2009 03:13

Re: sigmentation fault
 
actually, I wasn't assigning a number to a point. *i is dereferencing a pointer. *i = 3 is to let i point to value 3. I'm still confused why this caused the seg fault.

This is a simplified version of the problem. Originally, I wanted to manipulate a string parameter in a function. It seems as long as I change the value pointed by a pointer (this pointer is a parameter to a function), seg fault appears...

Amar_Raj 25Aug2009 10:22

Re: sigmentation fault
 
Since it is not initialized with valid address and you are accessing that address to modify the value, the segmentation fault occurs! Just allocate some valid address and try... it should work.

SaswatPadhi 25Aug2009 12:44

Re: sigmentation fault
 
Quote:

Originally Posted by c_user (Post 55967)
see friend as per my logic u cannot assign a no. to a pointer so its showing u the fault....
>>*i=3 is the wrong statement....
hav a gud day...

He is not assigning the int to the pointer. He is actually de-referencing the the pointer with *, and assigning 3 to the address to which the pointer is pointing.

Quote:

Originally Posted by Amar_Raj (Post 56014)
Since it is not initialized with valid address and you are accessing that address to modify the value, the segmentation fault occurs! Just allocate some valid address and try... it should work.

Right. :)
You are de-referencing a pointer which is not assigned to any address.

It's always a good practice to check the pointer b4 assigning values to it. Like this :

Code: C++

void test(int *i) {
  if(i != NULL) { *i = 3; }
  else              { printf("ERROR :: Pointer does not point to a valid address !\n"); }
}


inspire 25Aug2009 21:24

Re: sigmentation fault
 
Thank you all!


All times are GMT +5.5. The time now is 19:02.