Malloc / free in C ++: why does Free not accept const void *, and is there a better way?

The interaction of C ++ 11 code with some C callbacks, and I need to pass const char * const *, i.e. an array of strings. Here is a cut out 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 developed how to use mallocin C ++, but I am stuck on freebecause it tells me: "incorrect conversion from" const void * to "void * [-fpermissive]"

My first reaction was, "Oh, why do you need all this, all you have to do is release the pointer." The second reaction was to simply throw it away. But this is rejected by the compiler:

free( const_cast<void*>(names) );

And this too:

free( static_cast<void*>(acctnames) );

eg. "invalid static_cast of type 'const char * const * for type' void *".

"ole C cast":

free( (void*)(acctnames) );

, - ? (valgrind : " - ", !)

P.S. g++ 4.8.1 Linux.

: , free() , const : C ( barak manos answer ).

+4
2

const_cast const volatile; . , static_cast , . void* , :

free( const_cast<const char**>(names) );

const_cast, static_cast ( reinterpret_cast ).

C const_cast, static_cast, . , : , reinterpret_cast, , .

- : X* X const* , :

const char ** names = static_cast<const char **>(malloc( sizeof(char*) * cnt));
the_c_function(names); // OK - adds const
free(names);           // OK - no const to remove

, ++, malloc ( API C , , ​​ malloc):

std::vector<const char*> names(cnt);
the_c_function(names.data());
+8

, .

free(p), p , p.

:

static void* _head;
...
void free(void* p)
{
    *(int*)p = (int)_head;
    _head = p;
}

, , const void* p.

(_head), (_tail). , p const ( , ).

+2

Source: https://habr.com/ru/post/1539898/


All Articles