Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real implementation where sizeof(size_t) < sizeof(unsigned int)

Tags:

c

sizeof

size-t

I know that the C standard allows for implementations where

(sizeof(unsigned) > sizeof(size_t))

or

(sizeof(int) > sizeof(ptrdiff_t))

is true. But are there any real implementations where one of these is true?

Background

I wrote a function similar to asprintf() (since asprintf() is not portable), and snprintf() return an int but needs a size_t argument, so should I check if leni (shown below) is not less than SIZE_MAX in this code?

va_copy(atmp,args)
int leni = vsnprintf(NULL,0,format,atmp); //get the size of the new string
va_end(atmp);
if(leni<0)
  //do some error handling
if(leni>=SIZE_MAX) //do i need this part?
  //error handling
size_t lens = ((size_t)leni)+1;
char *newString = malloc(lens);
if(!newString)
  //do some error hanling
vsnprintf(newString,lens,format,args)!=lens-1)
like image 410
12431234123412341234123 Avatar asked Aug 24 '16 12:08

12431234123412341234123


1 Answers

While the standard doesn't forbid that INT_MAX won't be smaller than SIZE_MAX, the function vsnprintf guarantees that the returned value will not be greater than SIZE_MAX.

If the functions succeeds, then the return value must be less than its second argument1. This argument has the type size_t, thus the return value must be less than SIZE_MAX.2.

And if you're not convinced, you can always use preprocessor directive that evaluates INT_MAX > SIZE_MAX, and then include the needed code that checks the result of vsnprintf.


1 The identifier n mentioned in the standard citation below, is the second argument to vsnprintf.

2 (Quoted from: ISO/IEC 9899:201x 7.21.6.12 The vsnprintf function 3)
The vsnprintf function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a neg ative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.

like image 200
2501 Avatar answered Nov 15 '22 05:11

2501