指针(地址)可以为负数吗? [英] Can a pointer (address) ever be negative?

查看:47
本文介绍了指针(地址)可以为负数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我希望能够为失败未初始化返回特殊值(它在成功时返回一个指针).

I have a function that I would like to be able to return special values for failure and uninitialized (it returns a pointer on success).

目前它返回 NULL 表示失败,-1 表示未初始化,这似乎有效……但我可能在欺骗系统.IIRC,地址总是正数,不是吗?(尽管由于编译器允许我将地址设置为 -1,这看起来很奇怪).

Currently it returns NULL for failure, and -1 for uninitialized, and this seems to work... but I could be cheating the system. IIRC, addresses are always positive, are they not? (although since the compiler is allowing me to set an address to -1, this seems strange).

我的另一个想法(如果 -1 有风险)是 malloc 一个字符 @ 全局范围,并将该地址用作哨兵.

Another idea I had (in the event that -1 was risky) is to malloc a char @ the global scope, and use that address as a sentinel.

推荐答案

不,地址并不总是正数 - 在 x86_64 上,指针是符号扩展的,地址空间对称地聚集在 0 附近(尽管这对于否定"地址是内核地址).

No, addresses aren't always positive - on x86_64, pointers are sign-extended and the address space is clustered symmetrically around 0 (though it is usual for the "negative" addresses to be kernel addresses).

然而,这一点大多没有实际意义,因为 C 只定义了 <> 指向同一对象的一部分的指针之间的指针比较的含义,或者一个数组的末尾.指向完全不同对象的指针不能进行有意义的比较,除非完全相等,至少在标准 C 中 - if (p < NULL) 没有明确定义的语义.

However the point is mostly moot, since C only defines the meaning of < and > pointer comparisons between pointers that are to part of the same object, or one past the end of an array. Pointers to completely different objects cannot be meaningfully compared other than for exact equality, at least in standard C - if (p < NULL) has no well defined semantics.

您应该创建一个具有静态存储持续时间的虚拟对象,并将其地址用作您的未初始化值:

You should create a dummy object with static storage duration and use its address as your unintialised value:

extern char uninit_sentinel;
#define UNINITIALISED ((void *)&uninit_sentinel)

保证在整个程序中都有一个唯一的地址.

It's guaranteed to have a single, unique address across your program.

这篇关于指针(地址)可以为负数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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