Imagine I have this C function (and the corresponding prototype in a header file)
void clearstring(const char *data) {
char *dst = (char *)data;
*dst = 0;
}
Is there Undefined Behaviour in the above code, casting the const away, or is it just a terribly bad programming practice?
Suppose there are no const-qualified objects used
char name[] = "pmg";
clearstring(name);
The attempt to write to
*dstis UB if the caller passes you a pointer to a const object, or a pointer to a string literal.But if the caller passes you a pointer to data that in fact is mutable, then behavior is defined. Creating a
const char*that points to a modifiablechardoesn’t make thatcharimmutable.So:
That is, your function is extremely ill-advised, because it is so easy for a caller to cause UB. But it is in fact possible to use it with defined behavior.