- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
假设我们有:
char *a = malloc(sizeof(char*));
char *b = realloc(a,sizeof(char*));
我们可以肯定地说 b
不会与 a
互为别名吗? realloc
引用页说
The original pointer ptr is invalidated and any access to it is undefined behavior (even if reallocation was in-place).
那么我可以将 b
标记为不是别名 a
因为我们不能再合法访问 a
了吗?然而,这可能会导致有问题的优化,其中将消除以下分支:
if (a == b)
something..
根据我的理解,a == b
本身的比较将是 UB,那么这在技术上是正确的优化吗?
最佳答案
释放后,a
的值是不确定的。
n1570-§6.2.3 (p2):
[...] If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
如果这个不确定的值变成陷阱表示,比较 a == b
将导致未定义的行为。
请注意,当指针传递给free
时,指针指向的对象的生命周期结束。
延伸阅读:
1. Why isn't a pointer null after calling free?
2. A dangling pointer is indeterminate .
关于我们可以肯定地说 realloc 的结果不会与原始指针互为别名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47975074/
您好,我有一个表,其中包含组织每个成员的状态记录。我想根据表中提供的最新状态找出哪些成员仍然活跃。Hee 是表中记录的示例: 最佳答案 您可以使用 where 子句中的子查询获取每个名称的最后状态:
对 BDD 和 RSpec 相当陌生,我真的很好奇人们在编写 RSpec 测试/示例时通常会做什么,特别是因为它涉及同一事物的正面和负面测试。 以验证用户名和有效用户名仅包含字母数字字符的规则为例。
我是一名优秀的程序员,十分优秀!