c - What is the proper way to use memset on a struct element? -


i'm trying use memset on struct element so:

memset( &targs[i]->cs, 0, sizeof( xcpu ) ); 

however, doing gives me segmentation fault. neither understand why failing, nor how can make work. what proper way use memset on element of struct, , why method not work?

line allocates memory targs:

eargs **targs = (eargs **) malloc(p * sizeof(eargs *)); 

struct definitions struct element cs (xcpu_context) , struct targs (execute_args):

typedef struct xcpu_context {   unsigned char *memory;                 unsigned short regs[x_max_regs];       unsigned short pc;                     unsigned short state;                 unsigned short itr;                    unsigned short id;                    unsigned short num;                  } xcpu;  typedef struct execute_args {     int ticks;     int quantum;     xcpu cs; } eargs; 

you have allocated array of pointers in line

eargs **targs = (eargs **) malloc(p * sizeof(eargs *)); 

but haven't initialized elements themselves. segfault has nothing using memset on fields of struct, instead derives using uininitialized memory (assuming don't have loop initialize each eargs object after allocate array of pointers).

instead, if wanted allocate dynamic array of p eargs objects (i'm using term "objects" loosely here), write

eargs *args = malloc(p * sizeof(eargs)); if (!args) {     /* exit error message */ } memset(&(args[i].cs), 0, sizeof(xcpu)); 

instead. note args dynamically allocated array of eargs objects, not dynamically allocated array of pointers, it's of type eargs * rather eargs **.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -