I came across int safe_alloc_realloc_n (void *ptrptr, size_t size, size_t count)
function, at Github/scratchpadRepos/gnulib, which is actually an older version of the official gnulib,
In that function, I found *(void **)ptrptr
weird,
With or without the cast, it contains a memory address, so is there any point of casting here,
CodePudding user response:
Why gnulib uses
*(void **) ptrptr
instead of proper, and without cast, usage
The argument is a void *
, doing *ptrptr
would try to assign to void
. void
is a void, you can't assign to it.
On POSIX systems you can cheat, all pointers have the same alignment and size. You can do int *a; *(void **)&a = some_value;
, although such code is very invalid according to C language.
The function takes a generic pointer void *
and then assigns to the pointer, so that you can int *a; safe_alloc_realloc_c(&a, ...)
pass a pointer to any pointer type. Otherwise you would have to create a separate function for every type safe_alloc_realloc_c_int(int **, ...)
safe_alloc_realloc_c_char(char **, ...)
etc.
Have same functionality,
No. malloc
allocates memory. new
allocates the memory and creates an object, calling object constructor and starting object lifetime.