A
ais523
I'm trying to write a function that does some realloc-style
modification of a pointer. The function itself works, but I'm having
some problems with the prototype. This is a simple example of the sort
of thing I want to do (not the complete code, that works but is
technically UB).
#include <stdlib.h>
void indirectmalloc(void** ptr, size_t s)
{
*ptr=malloc(s);
return;
}
int main(void)
{
char* a;
int* b;
indirectmalloc(&a);
indirectmalloc(&b);
free(a);
free(b);
return 0;
}
but although all pointers are freely castable to and from void*, not
all pointers-to-pointers are freely castable to and from void**, so
this is UB.
One compiler I use allows &(void*)a, but this is nonstandard. Is there
a portable way of doing this without relying on temporary void*s?
Should I use a #define macro instead? Although there are obviously
easier ways of writing the above code, I'd like to do something like
this (my actual code is more complicated; I'm not posting it because it
works, just invokes UB which happens to not be a problem on my
compiler).
modification of a pointer. The function itself works, but I'm having
some problems with the prototype. This is a simple example of the sort
of thing I want to do (not the complete code, that works but is
technically UB).
#include <stdlib.h>
void indirectmalloc(void** ptr, size_t s)
{
*ptr=malloc(s);
return;
}
int main(void)
{
char* a;
int* b;
indirectmalloc(&a);
indirectmalloc(&b);
free(a);
free(b);
return 0;
}
but although all pointers are freely castable to and from void*, not
all pointers-to-pointers are freely castable to and from void**, so
this is UB.
One compiler I use allows &(void*)a, but this is nonstandard. Is there
a portable way of doing this without relying on temporary void*s?
Should I use a #define macro instead? Although there are obviously
easier ways of writing the above code, I'd like to do something like
this (my actual code is more complicated; I'm not posting it because it
works, just invokes UB which happens to not be a problem on my
compiler).