sigmentation fault

Discussion in 'C' started by inspire, Aug 24, 2009.

  1. inspire

    inspire New Member

    Joined:
    Aug 24, 2009
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    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.
     
  2. c_user

    c_user New Member

    Joined:
    Aug 23, 2009
    Messages:
    86
    Likes Received:
    8
    Trophy Points:
    0
    Occupation:
    Php dev
    Location:
    Bhubaneswar
    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...
     
  3. inspire

    inspire New Member

    Joined:
    Aug 24, 2009
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    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...
     
  4. Amar_Raj

    Amar_Raj New Member

    Joined:
    Jun 17, 2009
    Messages:
    34
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Dev
    Location:
    Namma Bengaluru
    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.
     
  5. SaswatPadhi

    SaswatPadhi ~ Б0ЯИ Τ0 С0δЭ ~

    Joined:
    May 5, 2009
    Messages:
    1,342
    Likes Received:
    55
    Trophy Points:
    0
    Occupation:
    STUDENT !
    Location:
    Orissa, INDIA
    Home Page:
    http://www.crackingforfun.blogspot.com
    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.

    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:
    void test(int *i) {
      if(i != NULL) { *i = 3; }
      else              { printf("ERROR :: Pointer does not point to a valid address !\n"); }
    }
     
  6. inspire

    inspire New Member

    Joined:
    Aug 24, 2009
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Thank you all!
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice