加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – size_t添加中的溢出

发布时间:2020-12-16 03:47:50 所属栏目:百科 来源:网络整理
导读:我喜欢为VS.NET和GCC免费提供代码警告,我希望我的代码准备好64位. 今天我编写了一个处理内存缓冲区的小模块,并通过文件样式的接口提供对数据的访问(例如,您可以读取字节,写入字节,搜索等). 作为当前读取位置和大小的数据类型,我使用size_t,因为这似乎是最自
我喜欢为VS.NET和GCC免费提供代码警告,我希望我的代码准备好64位.

今天我编写了一个处理内存缓冲区的小模块,并通过文件样式的接口提供对数据的访问(例如,您可以读取字节,写入字节,搜索等).

作为当前读取位置和大小的数据类型,我使用size_t,因为这似乎是最自然的选择.我绕过警告,它也应该在64位工作.

以防万一:我的结构看起来像这样:

typedef struct
{
  unsigned char * m_Data;
  size_t          m_CurrentReadPosition;
  size_t          m_DataSize;
} MyMemoryFile;

size_t的签名似乎没有在实践中定义. Google代码搜索证明了这一点.

现在我处于两难境地:我想检查带有size_t的附加内容是否有溢出,因为我必须处理用户提供的数据,第三方库将使用我的代码.但是,对于溢出检查,我必须知道符号.它在实施中产生了巨大的差异.

那么 – 我应该如何在平台和编译器独立的方式编写这样的代码?

我可以在运行或编译时检查size_t的签名吗?那样可以解决我的问题.或者也许size_t首先不是最好的主意.

有任何想法吗?

编辑:我正在寻找C语言的解决方案!

解决方法

关于size_t是签名还是未签名和GCC(来自旧的GCC手册 – 我不确定它是否仍然存在):

There is a potential problem with the
size_t type and versions of GCC prior
to release 2.4. ANSI C requires that
size_t always be an unsigned type. For
compatibility with existing systems’
header files,GCC defines size_t in
stddef.h to be whatever type the
system’s sys/types.h defines it to
be. Most Unix systems that define
size_t in sys/types.h,define it to
be a signed type. Some code in the
library depends on size_t being an
unsigned type,and will not work
correctly if it is signed.

The GNU C library code which expects
size_t to be unsigned is correct. The
definition of size_t as a signed type
is incorrect. We plan that in version
2.4,GCC will always define size_t as an unsigned type,and the
‘fixincludes’ script will massage the
system’s sys/types.h so as not to
conflict with this.

In the meantime,we work around this
problem by telling GCC explicitly to
use an unsigned type for size_t when
compiling the GNU C library.
‘configure’ will automatically detect
what type GCC uses for size_t arrange
to override it if necessary.

如果你想要一个签名版本的size_t使用ptrdiff_t,或者在某些系统上有ssize_t的typedef.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读