在什么架构计算无效指针是不安全的? [英] On what architectures is calculating invalid pointers unsafe?

查看:135
本文介绍了在什么架构计算无效指针是不安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  int * a = new int [5]  -  1; 

此行本身根据C ++标准调用未定义的行为,因为a是一个无效的指针, - 结束。同时,这是一个零开销的方法,使1基于数组(第一个元素是a [1],我需要一个

我想知道如果这是我需要避免的东西,或者如果C ++标准只是保守支持一些奇怪的架构,我的代码永远不会运行反正。所以问题是,在什么架构这将是一个问题?是否有广泛的行为?



编辑:要看到上面的行确实调用了未定义的行为,请查看这个问题。 p>

编辑:Dennis Zickefoose指出,编译器被允许在未定义的行为被调用时做任何事情,所以编译器和CPU都必须提供超出C ++标准的保证,这个工作。我会将问题扩展到任何现代C ++编译器是否有这个问题。

解决方案

所有x86处理器,我们只是暂时不在最流行的操作系统中使用它。



如果使用分段的内存架构,我们为16位系统,分配不太可能返回地址 segment:0 。在这种情况下,你不能从该地址中减去任何内容!



这里是读取分段内存的起点,以及为什么不能加载无效段:



http://en.wikipedia.org/wiki/Segment_descriptor



你必须决定这不可能发生在你的代码,或者你也许可以定义一个重载的 operator [] 来处理您的偏移。


int* a = new int[5] - 1;

This line by itself invokes undefined behavior according to the C++ standard because a is an invalid pointer and not one-past-the-end. At the same time this is a zero overhead way of making a 1-based array (first element is a[1]) which I need for a project of mine.

I'm wondering if this is something that I need to avoid or if the C++ standard is just being conservative to support some bizarre architectures that my code is never going to run on anyway. So the question is, on what architectures will this be a problem? Are any of those widespread?

Edit: To see that the line above does indeed invoke undefined behavior, take a look at this question.

Edit: Dennis Zickefoose points out that compilers are allowed to do anything when undefined behavior is invoked, so both the compiler and the CPU have to offer guarantees beyond the C++ standard for code like this to work. I'm expanding the question to whether any modern C++ compilers have this issue.

解决方案

The hardware for doing the checks is present in all x86 processors, we are just not using it at the moment in the most popular operating systems.

If you use a segmented memory architecture, which we did for 16-bit systems, an allocation is not unlikely to return the address segment:0. In that case you just cannot subtract anything from that address!

Here is a starting point for reading about segmented memory and why loading an invalid segment is not possible:

http://en.wikipedia.org/wiki/Segment_descriptor

You have to decide if this unlikely to happen for your code, or if you perhaps can define an overloaded operator[] that handles the offset for you.

这篇关于在什么架构计算无效指针是不安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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