Question:
The purpose of type checking in this particular example (malloc)?
doodh
2010-06-18 12:25:55 UTC
In C, for example :

int *c;
c=(int*)malloc(30);

Here, the casting the void* returned by malloc to int*, is actually just making the compiler sure that the programmer knows what he is doing and he is doing that on purpose. Other than that, casting here doesn't achieve anything special. Is this right ?

isn't this the purpose of type casting, in general too ?
Three answers:
djp32563
2010-06-18 13:26:25 UTC
Pretty much so. Type casting here is a way of "ordering" the compiler to make the void pointer returned by malloc go into the int pointer c. In this case pretty harmless, but it can get dicey when dealing with more complex data types. Typecasting can cause all kinds of hard to trace bugs if you are not careful. For instance:



unsigned char B[10 ]// Array of 10 bytes

int *T;



T = (int *)& B; // fool compiler into treating &B as an int pointer

T[9] = 100; // PROBLEM!!!



This will result in a corrupted stack, Which will is BAD NEWS,but this code compiles with no errors because of the typecast.
ʃοχειλ
2010-06-18 19:44:35 UTC
You are perfectly right with one very small note. Most often, changing the (interpretation of) type of an expression is straight forward; like your example, an int* and a void* are the same size and nature; they just point to an object of different types. So, compiler does not do anything; it just lets the assignment take place.



On the other hand, some times casting is done with some sort of standard type conversion. For example,



int x = 20;

long y = 100;



long a;

int b;



a = (long) x ; // casting is not really necessary but automatically performs by compiler.

b = (int) y; // casting must be explicitly done by programmer.



Here, in both of the above expressions, casting is not just a simple requesting a permission from compiler for assignment like those of pointers. Compiler actually making a type conversion defined in the infrastructure routines of the compiler. For example, if long is a 64 bit integer data type, and int is 32 bit, then conversion (done by casting or automatically) from int to long would extend a 32 bit integer to 64 bit, and conversion (done by casting) from long to int would reduce its bits from 64 to 32 bit (with some risk of loosing data information).
The Phlebob
2010-06-18 19:51:37 UTC
In this case, the typecasting is the way the programmer tells the compiler that the assignment is intentional and not accidental. Just a way of avoiding a compiler warning or even error message.



Hope that helps.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...