是否未定义要丢弃函数参数的常数的行为? [英] Is it Undefined Behaviour to cast away the constness of a function parameter?

查看:210
本文介绍了是否未定义要丢弃函数参数的常数的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象我有这个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;
}

在上述代码中有未定义的行为, c $ c> const away ,或者这是一个非常糟糕的编程实践吗?

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 如果调用者传递了指向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 immutable。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆