tags:

views:

133

answers:

4

Hello,

gcc 4.4.4 c89

I have the following structure.

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

int main(void)
{
    struct device_sys dev_sys[NUM_DEVICES];

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

    return 0; 
}

I get a stack dump when I call memset. Is this not the correct way to initialize an structure array?

Many thanks for any advice,

+4  A: 

There's a typo in your code. Fix:

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

Picking good names avoid half the bugs. I'd recommend "devices".

Hans Passant
probably even safer way:`memset(dev_sys, 0, sizeof(dev_sys));`
Drakosha
@Hans Passant: This is only valid in C++.
Lucas
Yes, corrected.
Hans Passant
+1  A: 

You have to pass the sizeof operator the type and not the variable.

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

I prefer to use typedef for the struct.

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

The you can use memset as follows:

    memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));
Lucas
+8  A: 

Either

memset(&dev_sys, 0, sizeof dev_sys);

or

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

Or, if you prefer

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

but not what you have in your original variant.

Note, that in your specific case in all variants you can use either &dev_sys or dev_sys as the first argument. The effect will be the same. However, &dev_sys is more appropriate in the first variant, since if follows the memset(ptr-to-object, object-size) idiom. In the second and third variants it is more appropriate to use dev_sys (or &dev_sys[0]), since it follows the memset(ptr-to-first-element, number-of-elements * element-size) idiom.

P.S. Of course, instead of using all that hackish memset trickery, in your particular case you should have just declared your array with an initializer

struct device_sys dev_sys[NUM_DEVICES] = { 0 };

No memset necessary.

AndreyT
OP said c89, isn't that initializer c99?
bstpierre
@bstpierre: No. Why? Aggregate initializers were in C since the beginning of times (well, almost).
AndreyT
robUK
AndreyT
@AndreyT - sorry, I was confusing that with the gcc warning "missing braces around initializer" that you'll get with that initializer. You're right, no syntax change there.
bstpierre
robUK
+1  A: 

For an array, sizeof gets you the entire size of the array, not the size of an individual element. The sizeof operator is one of the few places where an array is not treated as a pointer to its first element.

Thom Smith