...
In this noncompliant example, an object of type float
is incremented through an int *
. Using the maximum units in last position is often done as a way The unit in the last place can be used to get the next representable value for a floating-point numbertype. However, accessing an object through a pointer of incompatible types is undefined behavior.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> void f(void) { if (sizeof(int) == sizeof(float)) { float f = 0.0f; int *ip = (int *)&f; printf("float is %f\n", f); (*ip)++; printf("float is %f\n", f); } } |
...
In this noncompliant code example, an array of two shorts values of type short
is treated as an integer and assigned an integer value. The resulting value of the two shorts is undefinedvalues are indeterminate.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> void func(void) { short a[2]; a[0]=0x1111; a[1]=0x1111; *(int *)a = 0x22222222; printf("%x %x\n", a[0], a[1]); } |
...
Noncompliant Code Example
In this noncompliant code example, a gadget
object is allocated, then realloc()
is called to create a widget
object using the memory from the gadget
object. Although reusing memory to change types is acceptable, accessing the memory copied from the original object is undefined behavior.
...