Mario Charest wrote:
What do you prefer and why?
char *p;
p = malloc(SIZE);
…
memset( p,0, sizeof (char) * SIZE )
Since sizeof(char) is guaranteed to be one, it’s redundant here. I
think it’s a good habit to pass exactly the same expression to memset()
that you passed to malloc() – it makes it more obvious that you’re
memsetting exactly the correct amount of memory.
or
memset( p, 0, sizeof( *p ) * SIZE );
I prefer this one, especially when p is not a char pointer. It makes it
obvious that no matter what type of objects p points to, you’re
memsetting SIZE such objects. With an explicit type in the sizeof,
there’s a chance that some day you may change the type of p but forget
to change the type in the sizeof.
======================
char x[SIZE];
memset( x, 0, sizeof x );
This one guarantees that you’re memsetting all the bytes of x, provided
that x is an array. If you later change x to be a pointer, this will
happily memset the first four bytes of whatever it points to, which is
not a good thing.
Personally, I prefer
memset( &x, 0, sizeof(x) );
because it works no matter whether x is an array, a structure, or a
simple scalar. If you change the array into a pointer some day but
forget to allocate memory, this will set the pointer to NULL, and
hopefully, a crash will tell you what you’re missing.
or
memset ( x, 0, sizeof x * SIZE )
This one is wrong… Did you mean sizeof(x[0]) * SIZE, or something
like that?
or
memset ( x, 0, sizeof char * SIZE );