Casting and type safety
malloc
returns a void pointer (void *
), which indicates that it is a pointer to a region of unknown data type. One may "cast" (see type conversion) this pointer to a specific type, as in
int *ptr = (int*)malloc(10 * sizeof (int));
When using C, this is considered bad practice; it is redundant under the C standard. Moreover, putting in a cast may mask failure to include the headerstdlib.h
, in which the prototype formalloc
is found. In the absence of a prototype formalloc
, the C compiler will assume thatmalloc
returns anint
, and will issue a warning in a context such as the above, provided the error is not masked by a cast. On certain architectures and data models (such as LP64 on 64 bit systems, wherelong
and pointers are 64 bit andint
is 32 bit), this error can actually result in undefined behaviour, as the implicitly declaredmalloc
returns a 32 bit value whereas the actually defined function returns a 64 bit value. Depending on calling conventions and memory layout, this may result in stack smashing.
Sillinesssss...
No comments:
Post a Comment