gpt4 book ai didi

我们可以肯定地说 realloc 的结果不会与原始指针互为别名吗?

转载 作者:太空狗 更新时间:2023-10-29 15:28:23 29 4
gpt4 key购买 nike

假设我们有:

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com