On 18 févr. 2011, at 15:12, Philip Graham Willoughby wrote:

> Adding casts to get rid of warnings is usually the wrong answer in my 
> experience. Certainly you should never cast the return value of a function 
> call because that hides the problems you get when it's implicitly returning 
> int because a required header is missing. I used to see a lot of C code 
> (usually from Windows programmers - does MSVC encourage this?) which has 
> stuff like this all over the place:
> 
>       struct something *fred = (struct something *)malloc(sizeof(struct 
> something));
> 
> Casting the return from malloc is never necessary - void * is assignable to 
> any non-function pointer type by definition.
> 
> It becomes an extremely bad idea when you're building on a platform with 
> 64-bit pointers and a 32-bit int (such as everything I use) and you have the 
> optimiser turned on – in this case if <stdlib.h> isn't included none of your 
> allocations will work properly and your program will crash.
> 
> Best Regards,
> 
> Phil Willoughby
> -- 

My pure C must be rusted. Could you please elaborate why this line breaks with 
64-bit pointers and 32-bit ints?

fred is a 64 bit pointer of type struct something *
malloc returns a 64 bit pointer of type void *
casting that pointer to struct something * makes it a 64-bit pointer of type 
struct something *, which is then assigned to fred.

I can't see how 64-bitness of pointers can hurt.

Similarly, malloc takes one argument of type size_t. On such a platform size_t 
is probably defined as long (or long long), but that is irrelevant, because the 
sizeof intrinsic is defined as returning a size_t as well. Now even if size_t 
is defined as int, this would only have an impact for structs larger than 2^31 
bytes, which are few are far between, and that impact would be unrelated to the 
typecast.

I can't see how 32-bitness of ints can hurt.

What did I miss?

JD


_______________________________________________
sqlite-users mailing list
sqlite-users@sqlite.org
http://sqlite.org:8080/cgi-bin/mailman/listinfo/sqlite-users

Reply via email to