How can I convert to size_t from int safely?

Assigning int size_t (or using it in malloc) in GCC raises the following warning:

warning: converting to 'size_t' from 'int' may change the sign of the result [-Wsign-conversion]

To solve this problem, I would like to wrap the conversion in a function that first checks the conversion is correct and then performs the listing.

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; } 

Did I miss something? Is there a safe conversion library that already exists?

The closest thing I can find is Microsoft Intsafe.h , but it apparently only applies to Win32 types.

EDIT Changed as a comment in chux.

+5
source share
1 answer

To avoid compiler warnings in GCC, restrict the action performed by a single cast operation to one of the following:

  • truncation or expansion
  • discard signed or unsigned information
  • discard a constant or non-constancy

size_t is always an unsigned type large enough to hold a pointer to a void. Casting from int to size_t involves two casting operations: extend, and then drop the subscription.

Here are two functions that do not generate compiler warnings (with "-Wall -Werror -Wextra") in GCC 4.8.3. They return an inline failure (via sentinel values), and not an additional 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); } 
+3
source

Source: https://habr.com/ru/post/1209138/


All Articles