Thread: Segmentation fault when initializing struct field by field

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    72

    Segmentation fault when initializing struct field by field

    Hi All

    consider the following initialization of a struct:

    Code:
    #include <stddef.h>
    #include <stdlib.h>
    #include <regex.h>
    #include <stdio.h>
    #include <string.h>
    
    struct CONFIG
     {
        int  *nos ;
        char *data_dir ;
        int *ratio ;
        regex_t *regex_int ;
        regex_t *regex_float ;
     } *_myconfig ;
    
    int main(void) {
      _myconfig = (struct CONFIG*)malloc(sizeof(_myconfig)) ;
      _myconfig->regex_int = calloc(1, sizeof(regex_t)) ;
      _myconfig->regex_float = calloc(1, sizeof(regex_t)) ;
      regcomp( _myconfig->regex_int, "[[:digit:]]+$", REG_EXTENDED | REG_NOSUB ) ;
      regcomp( _myconfig->regex_float, "^[[:digit:]]+\\.[[:digit:]]+$", REG_EXTENDED | REG_NOSUB ) ;
    
      printf("so far so good?") ;
      return 0;
    }
    If you run this code you'll get an Segmentation fault. However when I change the order of fields in the struct like

    Code:
    struct CONFIG
     {
        int  *nos ;
        char *data_dir ;
        regex_t *regex_int ;
        regex_t *regex_float ;
        int *ratio ;
     } *_myconfig ;
    Any suggestions whats happening here ?

    cheers
    LuCa

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Code:
     _myconfig = (struct CONFIG*)malloc(sizeof(_myconfig)) ;
    Well, that's not going to work. You need to have enough room for an entire struct, and 4 bytes certainly isn't. You should use sizeof(*_myconfig).

    (Edit: And there's no good reason to cast the result of malloc.)
    Last edited by tabstop; 06-07-2009 at 08:44 AM.

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    72
    thats it, thanks!!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Re: Segmentation fault
    By turkish_van in forum C Programming
    Replies: 8
    Last Post: 01-20-2007, 05:50 PM
  2. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM
  3. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  4. Bi-Directional Linked Lists
    By Thantos in forum C Programming
    Replies: 6
    Last Post: 12-11-2003, 10:24 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM