J
James Kuyper
Yes. It compiles with a warning as expected. Not a great example of type
safety.
It's a lot better than it would be if no warning were mandated. An
implementation is free to reject such code - whether or not it actually
does so is a matter of QoI, outside the scope of the standard.
This code on the other hand compiles with no warnings:
#include <stdlib.h>
int main(void)
{
int *ptr = (int*) malloc(sizeof(long));
*ptr = 10;
short blah = *ptr;
free(ptr);
exit(EXIT_SUCCESS);
}
so please explain how C is a type safe language?
Type safety is not an absolute yes or no issue. Some languages have more
type safety than others. C has static type checking - in many different
contexts, a diagnostic is mandatory if different types are not
compatible. Implicit conversions are often safe conversions, the most
dangerous type conversions are required to be explicit (except those
pointer conversions which can be done using void* as an intermediate
type). There's plenty of room for improvement in C's type safety, but
it's still a lot better than having no type checking, or deferring type
checking until run-time (both of which I've seen in other languages).
The fact that malloc() returns a void pointer that can be cast to any
type destroys any type safety C may have.
No, it doesn't. It just adds another type-unsafe mechanism to a language
that has only a moderate amount of type safety without it.
lcc-win32's compile() looks to me like it compromises type safety much
more than malloc() does, which is what prompted my original comment. A
pointer to a function that might point have the wrong function type
seems much more serious to me than a pointer to an object that might
have the wrong object type; there's a larger variety of ways you can
have a mis-match, and a correspondingly larger number of different
failure modes available. It's not good, either way.