I didn't find an exact answer to this question so either it's a stupid question or just plain obvious. I would like to know if it would produce undefined behaviour.
I have some struct type defined:
typedef struct {
char string1[17];
char string2[33];
int someInt;
float someFloat;
} my_struct_t;
I need multiple instances of that struct (like you'd have in struct array), but the number of objects is unknown at compile time.
Is it correct to initialize it like this?
my_struct_t *myStruct;
size_t noOfElements;
size_t completeSize;
int index;
/* ...code which sets the number of elements at runtime... */
completeSize = sizeof(my_struct_t) * noOfElements;
myStruct = malloc(completeSize);
memset(myStruct, 0, completeSize);
/* ...and then access it as if it were an array...*/
myStruct[index].someInt = 10; // index < noOfElements
Is it safe to do this? The memset()
part is what I'm worried about.
Is it safe to do this? The memset() part is what I'm worried about.
Yes, it's safe, in the sense that this won't cause any undefined behaviour (buffer overflows, uninitialised values, etc.).
However, it won't necessarily set your values to zero. memset
sets the bits to 0, but this isn't necessarily the same as setting e.g. a float
to a value of 0
(although in practice, it will be fine on most normal platforms).