Tichodroma said:
#include <stdlib.h>
int main() {
const double
*x ;
x = (double *) malloc(4 * sizeof(double)) ;
free(x) ;
return 0 ;
}
Under gcc this generates a warning:
tmp.c:5: warning: passing argument 1 of ‘free’ discards qualifiers
from pointer target type
Should I understand from the warning that there's some other way I
should free const'ed memory, and if so how?
First, a couple of (mostly stylistic) suggestions:
"int main()" is better written as "int main(void)".
The malloc line is better written as:
x = malloc(4 * sizeof *x);
for reasons that have been explained here at length.
As to your question, what is the purpose of the "const" in the
declaration of x? It says that x is a pointer to a read-only object
of type double. If you're allocating an array of 4 doubles,
presumably you want to be able to write to them. And since calling
free() actually destroys the double objects, that violates their
constness. (The compiler doesn't necessarily know what free() does,
but it can see that there's no "const" in free's parameter
declaration.)
Usually when you declare a pointer to const <whatever>, you initialize
it to point to something that you don't intend to modify; the const
promises the compiler that you won't modify the target object via that
pointer.
You should use a double*, not a const double*, for malloc and free.
If you want to make a const double* visible to other code, so the
other code won't accidentally clobber the array elements, you can make
a copy of the double* pointer:
#include <stdlib.h>
int main(void)
{
double *private;
const double *public;
private = malloc(4 * sizeof *private);
public = private;
/*
* Do what you like with public *other than* modifying
* the array elements.
*/
free(private);
return 0;
}