This morning we found an old chunk of code that was causing a library call to crash.
struct fred
{
int a;
int b;
int c;
};
fred fred[MAX_SIZE+1];
memset( fred, 0, sizeof(fred) * MAX_SIZE+1 );
It appears that the sizeof(fred) may have been the full array size, rather than the structure size, as it was overwriting a great deal of memory.
The fact that it compiled without warning on several different systems seemed odd.
Is there a correct semantic for this case where the type and variable name are colliding?
or is this some sort of undefined behavior? or just a defect?
Number one would be, don’t do this as it’s confusing – but you’ve already discovered this.
The variable hides the name of the struct, but you can still use
struct fredto refer to the type.e.g.
Alternatively, why not just use the size of the complete object. That way your
memsetcall is robust in the face of changes to either the array size or type. You can do:You must have the parentheses when using a type id with
sizeofbut it’s not needed when you use an object.