Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
Dereferencing a void pointer

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Yes this code is legal and does not cause undefined behaviour (unless malloc returns NULL).

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!