简体   繁体   中英

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

I'm trying to use memset on a struct element like so:

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

However, doing so gives me a segmentation fault. I neither understand why this is failing, nor how I can make it work. What is the proper way to use memset on an element of a struct, and why does my method not work?

Line which allocates memory for targs:

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

Struct definitions for struct element cs (xcpu_context) and 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 an array of pointers in the line

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

but you haven't initialized the elements themselves. So this segfault has nothing to do with properly using memset on the fields of a struct, but instead derives from using uininitialized memory (assuming that you don't have a loop to initialize each eargs object after you allocate the array of pointers).

Instead, if you wanted to allocate a dynamic array of p eargs objects (I'm using the term "objects" loosely here), you would write

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

instead. Note that args is a dynamically allocated array of eargs objects, not a dynamically allocated array of pointers, so it's of type eargs * rather than eargs ** .

Your memory allocation line doesn't allocate any memory for any structures, only for pointers to structures. If you want to allocate memory for that whole array, you need to add a loop to allocate memory for the structures themselves:

for (i = 0; i < p; i++)
    targs[i] = malloc(sizeof(eargs));

Once you actually have structures to operate on, your memset() call should be fine.

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