抛弃函数参数的常量是未定义的行为吗? [英] Is it Undefined Behaviour to cast away the constness of a function parameter?
问题描述
假设我有这个 C 函数(以及头文件中的相应原型)
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;
}
上述代码中是否存在未定义行为,将 const
丢弃,还是只是一种非常糟糕的编程习惯?
Is there Undefined Behaviour in the above code, casting the const
away, or is it just a terribly bad programming practice?
假设没有使用 const 限定的对象
Suppose there are no const-qualified objects used
char name[] = "pmg";
clearstring(name);
推荐答案
尝试写入 *dst
是 UB if 调用者将指针传递给 const对象,或指向字符串文字的指针.
The attempt to write to *dst
is UB if the caller passes you a pointer to a const object, or a pointer to a string literal.
但是如果调用者传递给你一个指向实际上是可变数据的指针,那么行为就被定义了.创建指向可修改 char
的 const char*
不会使该 char
不可变.
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 modifiable char
doesn't make that char
immutable.
所以:
char c;
clearstring(&c); // OK, sets c to 0
char *p = malloc(100);
if (p) {
clearstring(p); // OK, p now points to an empty string
free(p);
}
const char d = 0;
clearstring(&d); // UB
clearstring("foo"); // UB
也就是说,你的函数是非常不明智的,因为调用者很容易导致 UB.但实际上可以将其用于已定义的行为.
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.
这篇关于抛弃函数参数的常量是未定义的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!