c - 获取未初始化指针的地址是未定义的行为吗?

标签 c pointers language-lawyer undefined-behavior

N1570 指出这是未定义的行为:

§J.2/1 The value of an object with automatic storage duration is used while it is indeterminate (6.2.4, 6.7.9, 6.8).

在这种情况下,我们的指针有一个不确定的值:

§6.7.9/10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;

然后我假定以下测试程序表现出未定义的行为:

#include <stdio.h>

int main(void) {
    char * ptr;
    printf("%p", (void*)&ptr);
}

我最关心的是 strtol 函数。先引用一下N1570中与endptr参数相关的部分:

§7.22.1.4/5 If the subject sequence has the expected form and the value of base is zero, the sequence of characters starting with the first digit is interpreted as an integer constant according to the rules of 6.4.4.1. [...] A pointer to the final string is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

§7.22.1.4/7 If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

这意味着 endptr 需要指向一个对象,并且 endptr 在某些时候被取消引用。例如,this implementation does so:

if (endptr != 0)
    *endptr = (char *)(any ? s - 1 : nptr);

然而,this highly upvoted answerthis man page 都显示 endptr 被传递给 strtol 未初始化。是否存在使这不是未定义行为的异常?

最佳答案

指针的值和它的地址不一样。

void *foo;

该指针有一个未定义的值,但是 foo 的地址,即 &foo 的值,必须是确定的(否则我们无法访问它).

至少这是我的直觉理解,我现在没有去挖掘标准,我只是觉得你看错了。

在谈论代码时,两者有时会混淆(“那个指针的地址是什么?”可以意思是“那个指针的值是什么,它指向什么地址?”)但是它们确实截然不同。

关于c - 获取未初始化指针的地址是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28587022/

相关文章:

c++ - 多态问题C++

c++ - 我可以在模板参数中声明一个 constexpr lambda 吗?

c - 将指向数组开头的指针与指向数组开头之前的相同类型的指针进行比较是否合法?

c++ - 需要帮助编写双哈希实现的查找函数

c - 将证书插入钥匙串(keychain)

c - 为什么我在不使用 malloc() 分配后不必使用 free()

c - 为什么指针传递给函数时会被设置为 (nil)?

c++ - 为什么这个表达式是无符号的?

Cordova项目和windows平台

c - 使用 gdb 进行 fork() 系统调用