Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid incompatible pointer warning when dealing with double-indirection

Assuming this program:

#include <stdio.h>
#include <string.h>

static void ring_pool_alloc(void **p, size_t n) {
    static unsigned char pool[256], i = 0;
    *p = &pool[i];
    i += n;
}

int main(void) {
    char *str;
    ring_pool_alloc(&str, 7);
    strcpy(str, "foobar");
    printf("%s\n", str);
    return 0;   
}

... is it possible to somehow avoid the GCC warning

test.c:12: warning: passing argument 1 of ‘ring_pool_alloc’ from incompatible pointer type
test.c:4: note: expected ‘void **’ but argument is of type ‘char **’

... without casting to (void**) (or simply disabling the compatibility checks)? Because I would very much like to keep compatibility warnings regarding indirection-level...

like image 289
fnawothnig Avatar asked May 03 '26 16:05

fnawothnig


1 Answers

Why don’t you change the method signature such that it returns the new pointer instead of passing it by pointer? In fact, just like regular malloc does:

static void * ring_pool_alloc(size_t n) {
    static unsigned char pool[256], i = 0;
    void *p = &pool[i];
    i += n;
    return p;
}

int main(void) {
    char *str = ring_pool_alloc(7);
    strcpy(str, "foobar");
    printf("%s\n", str);
    return 0;   
}
like image 72
Konrad Rudolph Avatar answered May 05 '26 10:05

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!