Call the Void Pointer

I have the code below:

#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 delete void pointer before dereferencing to avoid warning

warning: dereferencing a void * pointer

Am I breaking any rule by doing this or is this code good?

+5
source share
2 answers

Yes, this code is legal and does not cause undefined behavior (if malloc does not return NULL ).

+6
source

In accordance with standard mandates, this code looks normal. a pointer to a character type can be used to indicate an object without violating the alias 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 low address byte of the object. Successive increments of the result, up to the size of the object, give pointers to the remaining bytes of the object.

+3
source

All Articles