Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double pointer conversions, passing into function with `const void **ptr` parameter

Tags:

c

pointers

gcc

GCC gives me folowing warning:

note: expected 'const void **' but argument is of type 'const struct auth **

Is there any case, where it could cause problems?

Bigger snippet is

struct auth *current;
gl_list_iterator_next(&it, &current, NULL);

Function just stores in current some void * pointer.

like image 502
KAction Avatar asked Sep 27 '12 12:09

KAction


1 Answers

The error message is clear enough: you are passing a struct auth ** where a void ** was accepted. There is no implicit conversion between these types as a void* may not have the same size and alignment as other pointer types.

The solution is to use an intermediate void*:

void *current_void;
struct auth *current;

gl_list_iterator_next(&it, &current_void, NULL);
current = current_void;

EDIT: to address the comments below, here's an example of why this is necessary. Suppose you're on a platform where sizeof(struct auth*) == sizeof(short) == 2, while sizeof(void*) == sizeof(long) == 4; that's allowed by the C standard and platforms with varying pointer sizes actually exist. Then the OP's code would be similar to doing

short current;
long *p = (long *)(&current);  // cast added, similar to casting to void**

// now call a function that does writes to *p, as in
*p = 0xDEADBEEF;               // undefined behavior!

However, this program too can be made to work by introducing an intermediate long (although the result may only be meaningful when the long's value is small enough to store in a short).

like image 134
Fred Foo Avatar answered Oct 16 '22 12:10

Fred Foo