Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to pass a void pointer to function that accepts a non-void pointer?

Very simply, is the following code safe/portable?

#include <stdio.h>
#include <stdlib.h>

int add(int *a, int *b)
{
  return *a + *b;
}

int main()
{
  int x = 2;
  int y = 3;

  void *ptr1 = &x;
  void *ptr2 = &y;

  fprintf(stdout, "%d + %d = %d\n", x, y, add(ptr1, ptr2));

  return EXIT_SUCCESS;
}

I've compiled this with -Wall -Werror and -Wextra and received no warnings; it seems to run fine.

like image 464
John Avatar asked Sep 11 '25 00:09

John


1 Answers

There's two things to consider:

  1. C allows the implicit conversion from a void pointer to any other object pointer type. So it's syntactically okay to pass those arguments.

  2. The type of the actual object being pointed to, and the type of the pointer the function expects, must satisfy strict aliasing constraints, otherwise your program is in undefined behavior land.

You are okay on both points. So your program is perfectly fine.

like image 185
StoryTeller - Unslander Monica Avatar answered Sep 12 '25 15:09

StoryTeller - Unslander Monica