I have the below code:
#include <inttypes.h>
#include <stdlib.h>
struct a
{
void *p;
};
int main(void)
{
struct a *ptr = malloc(sizeof(struct a));
ptr->p = malloc(sizeof(uint8_t));
*((uint8_t *) ptr->p) = 2;
return 0;
}
I am casting the void pointer before dereferencing to avoid the warning
warning: dereferencing ‘void *’ pointer
Am I breaking any rule by doing this or is this code good?
Yes this code is legal and does not cause undefined behaviour (unless malloc returns NULL).
As per the standard mandates, this code looks ok. a pointer to a character type can be used to point to the object without breaking the aliasing rule.
To quote the standard, chapter §6.3.2.3
[...]. When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.