如何安全地从int转换为size_t? [英] How can I convert to size_t from int safely?
问题描述
在GCC中将int分配给size_t(或在malloc中使用它)会产生以下警告:
Assigning an int to a size_t (or using it in malloc) in GCC produces the following warning:
警告:从"int"转换为"size_t"可能会更改结果的符号[-Wsign-conversion]
warning: conversion to 'size_t' from 'int' may change the sign of the result [-Wsign-conversion]
为解决这个问题,我想将转换包装到一个函数中,该函数首先检查转换是否有效,然后进行强制转换.
To solve this, I would like to wrap the conversion in a function that first checks if the conversion is valid, then does the cast.
这是我到目前为止所拥有的:
This is what I have so far:
/* Convert int src to size_t dst. */
/* Assumes dst points to valid size_t address. */
int safe_size_t_from_int(size_t *dst, int src) {
if(src < 0) return SAFE_ERROR_NEGATIVE;
if(SIZE_MAX < INT_MAX) {
if(src > (int)SIZE_MAX) return SAFE_ERROR_OVERFLOW;
}
*dst = (size_t)src;
return SAFE_SUCCESS;
}
我错过了什么吗?是否已经存在具有安全转换的库?
Am I missing anything? Is there a library with safe conversions that already exists?
The closest thing I can find is Microsoft Intsafe.h, but it appears to be for Win32 types only.
编辑已根据chux的评论进行了修改.
EDIT Modified as per chux' comment.
推荐答案
为避免在GCC中出现编译器警告,请将单个强制转换操作执行的操作限制为以下操作之一:
To avoid compiler warnings in GCC, limit the action performed by a single cast operation to one of the following:
- 截断或扩展
- 放弃有签名或无签名
- 放弃常态或非常态
size_t始终是一个无符号类型,其大小足以容纳void指针.从铸造将int转换为size_t涉及两个强制转换操作:扩展,然后强制丢弃带符号的字符.
size_t is always an unsigned type large enough to hold a void pointer. Casting from int to size_t involves two cast operations: extend, then cast away signed-ness.
这里有两个函数在GCC 4.8.3上不产生编译器警告(带有'-Wall -Werror -Wextra').它们以内联方式(通过哨兵值)返回失败,而不是通过额外的返回参数返回.
Here's two functions that produce no compiler warnings (with '-Wall -Werror -Wextra') on GCC 4.8.3. They return failure inline (via sentinel values), rather than in an extra return parameter.
int size_t2int(size_t val) {
return (val <= INT_MAX) ? (int)((ssize_t)val) : -1;
}
size_t int2size_t(int val) {
return (val < 0) ? __SIZE_MAX__ : (size_t)((unsigned)val);
}
这篇关于如何安全地从int转换为size_t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!