Formally, you can never do that. The need to convert from a const-qualified pointer to a non-const qualified pointer always means that the program design is bad. Quite possibly the bad design lies in some 3rd party code which doesn't implement const
correctness properly.
In your specific case: either you need to modify the data and then you are possibly using the wrong type in the caller code. Or the function does not need to modify the data, in which case the function is badly written without const correctness.
In practice, C allows all manner of crazy casts, as long as you know the actual type of the data. In this case, data returned from malloc
has no type and it is read/write. It gets assigned an "effective type" at the first time you access that location.
So if Func
might modify the data but the caller will not, it is perfectly safe to write
int n=Func((char*)s);
It's all about what kind of data that is actually stored at the pointed-at location.