0

Consider:

int main()
{
    const char *p = new const char[10]();
    delete[] p;
}

No problems here.

Now consider:

int main()
{
    const char *p = static_cast<const char *>(calloc(10, 1));
    free(p);
}

Error:

prog.cpp: In function 'int main()':
prog.cpp:6:8: error: invalid conversion from 'const void*' to 'void*' [-fpermissive]
  free(p);

http://ideone.com/tyK7Ce

Any reason you can't do this?

In practice, you might allocate non-const but when you want to delete it, you may have only a const char * pointer left to do it with. delete[] lets you do it, but not free. Is there a reason for this?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
  • `const char *p` is a non-constant pointer to `const` memory. You can't write to the memory, but there is no problem `delete`'ing it (as long as it was `new`'ed). `new` and `delete` are part of the C++ language, the compiler knows that `delete` will not write to the memory, only free it. `free()`, on the other hand, is just a function like any other, and it is not declared to accept a const pointer as input, so you can't pass a `const` pointer to it. – Remy Lebeau Nov 10 '15 at 03:44
  • `free()` is a C function, not C++. Although in any case it would be odd to declare the object as const at the point of creation since that obviously makes it impossible to modify. `char* const;` on the other hand is fine, but obviously isn't the same as it makes the pointer constant, not the values within - though that has the benefit of ensuring that you can't mangle the address and pass `free()` a bad address. – Olipro Nov 10 '15 at 03:45
  • @RemyLebeau But free could be declared to take `const void *` – Neil Kirk Nov 10 '15 at 03:50
  • @Olipro `free()` is a function that exists in both C and C++. – Neil Kirk Nov 10 '15 at 03:51
  • @NeilKirk: per the C standards, `free()` is formally defined as taking a non-const `void*` pointer as input. All vendor implementations follow that definition. – Remy Lebeau Nov 10 '15 at 03:55

0 Answers0