...
The following non-compliant code demonstrates the perils of operating on data of improper types. It tries to increment an int typecast type cast as a float, and a float typecast type cast as an int, and displays the results.
Code Block | ||
---|---|---|
| ||
#include <assert.h>
#include <stdio.h>
int main(void) {
float f = 0.0;
int i = 0;
float *fp;
int *ip;
assert(sizeof(int) == sizeof(float));
ip = (int*) &f;
fp = (float*) &i;
printf("int is %d, float is %f\n", i, f);
(*ip)++;
(*fp)++;
printf("int is %d, float is %f\n", i, f);
return 0;
}
|
...
Code Block | ||
---|---|---|
| ||
#include <stdio.h>
int main(void) {
float f = 0.0;
int i = 0;
float *fp;
int *ip;
ip = &i;
fp = &f;
printf("int is %d, float is %f\n", i, f);
(*ip)++;
(*fp)++;
printf("int is %d, float is %f\n", i, f);
return 0;
}
|
...
Making invalid assumptions about the type of typecast type cast data, especially bit-fields can result in unexpected data values.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[ISO/IEC 9899-:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.7.2, "Type specifiers" \[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\] "STR Bit Representations" \[[MISRA 04|AA. C References#MISRA 04]\] Rule 3.5 \[[Plum 85|AA. C References#Plum 85]\] Rule 6-5 |
...