Interfacing C++11 code to some C callbacks, and I have to pass const char * const *
, i.e. an array of strings. Here is a cut-down version of my code:
int main(int,char**){
const int cnt = 10;
const char * const * names =
static_cast<const char * const *>(malloc( sizeof(char*) * cnt));
//... allocating names[0], etc. coming soon ...
the_c_function(names);
free(names);
return 0;
}
So I worked out how to use malloc
in C++, but I'm stuck on free
, as it tells me: "invalid conversion from ‘const void*’ to ‘void*’ [-fpermissive]"
My first reaction was "Eh? Why do you care, all you have to do is free the pointer." Second reaction was to just cast it away. But this gets rejected by the compiler:
free( const_cast<void*>(names) );
And this does too:
free( static_cast<void*>(acctnames) );
E.g. "invalid static_cast from type ‘const char* const*’ to type ‘void*’".
What does work is a good 'ole C cast:
free( (void*)(acctnames) );
Is that safe, or am I missing something here? (valgrind
tells me "All heap blocks were freed -- no leaks are possible", which is some comfort!)
P.S. Using g++ 4.8.1, on Linux.
UPDATE: explanation of why free()
wants a non-const pointer is here: Unable to free const pointers in C
(though I found barak manos's answer below clearer on that).