简体   繁体   中英

Memset In C Using Sizeof Operator :

Here is a struct :

typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;

For memset, which one should be used from below ?

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));

or

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));

What are the differences ?

I like to use objects as arguments to sizeof

struct whatever *ptr;
/* ... */
ptr = malloc(nelems * sizeof *ptr);
memset(ptr, 0, nelems * sizeof *ptr);

The advantage over using a parenthesized type is that the code only needs to be changed at one place should the type of the data change

struct before_change *ptr;
/* ... */
ptr = malloc(nelems * sizeof (struct before_change));
memset(ptr, 0, nelems * sizeof (struct before_change));

dev_sys is a pointer. sizeof(dev_sys) will just give you size of the pointer for your platform.

如果将dev_sys分配为(NUM_DEVICES * sizeof(device_sys)) memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys))应该可以工作

Definitely

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));

There are a few cases, if you have:

1) Static array, using sizeof in that context:

device_sys dev_sys[NUM_DEVICES] = { /* init data * };
...
sizeof(dev_sys);

In this case, sizeof operator will give the entire size of the array, so you will essentially end up with:

NUM_DEVICES * (NUM_DEVICES * sizeof(device_sys))

2) or you have a dynamically allocated piece of memory acccessed through a pointer, OR you are in the context of a function call where dev_sys is passed as a function argument. Either way:

sizeof(dev_sys) will give the size of a pointer (in the first, because it IS a pointer, in the second, due to pointer decay), whcih will most likely not be what you are after.

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(*dev_sys));

Always works as the way you've written it suggests dev_sys is either a pointer or an array. sizeof(*dev_sys) gives us the sizeof the first element.

In any case, I would write is as either

device_sys dev_sys[NUM_DEVICES];

memset(dev_sys, 0, (size_t) NUM_DEVICES * sizeof(*dev_sys));

or

device_sys *dev_sys = (device_sys *) calloc(NUM_DEVICES, sizeof(*dev_sys));

depending on if you want dev_sys on the stack or on the heap

Richard Stevens (Advanced Programming in the Unix Environment, etc) suggests bzero() or your own portable equivalent because it avoids the common bug of swapping memset() arguments. You could even make a single-arg macro ZERO(obj) that did bzero(obj, sizeof(*obj)) . Or ZERO(object) (memset (&(object), '\\0', sizeof ((object)))) perhaps is an alternative. Along those lines, nice way to make bugs less possible.

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