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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With