Help with seg fault

This is a discussion on Help with seg fault within the C Programming forums, part of the General Programming Boards category; This code runs fine in Windows, but seg faults in FreeBSD. Code: #include <stdio.h> #include <stdlib.h> #include <unistd.h> struct s1 ...

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    119

    Help with seg fault

    This code runs fine in Windows, but seg faults in FreeBSD.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    
    struct s1
    {
      unsigned int num;
    };
    
    typedef struct my_s
    {
      struct s1 *foo;
      unsigned char[100];
    }my_t;
    
    int main()
    {
       my_t *bar;
    
      bar = (my_t *)malloc(sizeof(my_t));
      bar->foo->num = 10;
    
      printf("%d",bar->foo->num);
      reeturn 0;
    }
    The red is what causes the seg fault. Anyone have any idea what the problem is?

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by homer_3 View Post
    The red is what causes the seg fault. Anyone have any idea what the problem is?
    bar->foo does not have any memory assigned. You need to malloc all your pointers, not just one.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    119
    Ah. That got it, thanks. Funny how it's not needed in Windows.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,914
    Quote Originally Posted by homer_3
    Funny how it's not needed in Windows.
    It is needed on Windows too. It just so happened that it did not crash your program, but maybe it would at some other time.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fscanf seg fault
    By mercuryfrost in forum C Programming
    Replies: 19
    Last Post: 08-20-2009, 01:22 PM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  4. weird seg fault
    By Vermelho in forum C Programming
    Replies: 3
    Last Post: 05-10-2008, 08:27 PM
  5. Seg Fault Problem
    By ChazWest in forum C++ Programming
    Replies: 2
    Last Post: 04-18-2002, 03:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21