简体   繁体   中英

Seg fault when trying to access member of structure array

typedef struct abc {
  unsigned int pref;
  unsigned int port;
  char *aRecordIp;
    int index;
    int count;
}abc_t;

typedef struct xyz {
        abc_t *ab;
        int index;
        int count;
}xyz_t;


int Lookup (char *lookup,xyz_t **handle) {

*handle = (xyz_t *)malloc(sizeof(xyz_t *));
(*handle)->ab = (abc_t *) malloc(5*sizeof(abc_t *));
//
(*handle)->ab[0].pref = 10;  //seg fault here
}


void *myhandle; 

// this is a void pointer and I cannot change that as it is used elsewhere too

char lookup;


Lookup(&lookup, &myhandle);

// I get a warning here which is obviuous but how do I take care of that

(*handle)->ab = (abc_t *) malloc(5*sizeof(abc_t *));

Should probably be:

(*handle)->ab = (abc_t *) malloc(5*sizeof(abc_t));

In C you don't need that cast though, since void* casts implicitly to any kind of pointer, so:

(*handle)->ab = malloc(5*sizeof(abc_t));

is enough.

Also, make sure you check the return value of all malloc calls.

(abc_t *) malloc(5*sizeof(abc_t *)); should be (abc_t *) malloc(5*sizeof(abc_t)); . You are requesting for space of 5 pointers rather than space for 5 strucures.

That error is a good reason to prefer the ptr = malloc (count * sizeof *ptr); notation; the compiler already knows the type and size of an expression, so you won't have to specify that again :

int Lookup (char *lookup,xyz_t **handle) {

  *handle = malloc(sizeof **handle);
  (*handle)->ab = malloc(5 * sizeof *(*handle)->ab );
  (*handle)->ab[0].pref = 10;  //seg fault here
}

Or, using array notation (just to avoid the ugly *(*handle) ) :

int Lookup (char *lookup,xyz_t **handle) {

  *handle = malloc(sizeof **handle);
  (*handle)->ab = malloc(5 * sizeof (*handle)->ab[0] );
  (*handle)->ab[0].pref = 10;  //seg fault here
}

Note: I also removed the casts, which are not needed and potentially dangerous.

Also note that this stylistic correction will fix both the errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM