今天我编写了一个处理内存缓冲区的小模块,并通过文件样式的接口提供对数据的访问(例如,您可以读取字节,写入字节,搜索等).
作为当前读取位置和大小的数据类型,我使用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语言的解决方案!
@R_403_323@
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 definessize_t
in
stddef.h
to be whatever type the
system’ssys/types.h
defines it to
be. Most Unix systems that define
size_t
insys/types.h
,define it to
be a signed type. Some code in the
library depends onsize_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 ofsize_t
as a signed type
is incorrect. We plan that in version
2.4,GCC will always definesize_t
as an unsigned type,and the
‘fixincludes’ script will massage the
system’ssys/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 forsize_t
when
compiling the GNU C library.
‘configure’ will automatically detect
what type GCC uses forsize_t
arrange
to override it if necessary.
如果你想要一个签名版本的size_t使用ptrdiff_t,或者在某些系统上有ssize_t的typedef.