3

So, I was writing an implementation of ye olde SHA1 algorithm in C (I know it's insecure, it's for the Matasano problems), and for some of the variables it's pretty crucial that they're exactly 32 bits long. Having read that unsigned long int is 32 bits by standard, I just used that, and then spent 4 hours trying to find why the hell my hashes were coming out all wrong, until I thought to see what sizeof(unsigned long int) came out to be. Spoiler, it was 64.

Now of course I'm using uint32_t, and always will in the future, but could someone (preferably, someone who has more discretion and less gullibility than I do) please point me to where the actual standards for variable sizes are written down for modern C? Or tell me why this question is misguided, if it is?

tckmn
  • 57,719
  • 27
  • 114
  • 156
gmoss
  • 1,019
  • 5
  • 17
  • 1
    The *actual* place will be the standard, and it and all respectable tutorials and references say that sizes are platform dependent. That's why the `[u]intxx_t` types were added. – Adam Dec 17 '15 at 02:52
  • 1
    The standard says that long int will be as big as or bigger than int, and tries very hard to avoid being too specific. The standard is the wrong place to look for the answer you seek. – William Pursell Dec 17 '15 at 02:54
  • On page 27 of the standard which I found here: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf, it says: Maximum value for an object of type `unsigned long int`: 2**32 - 1. Which seems pretty specific to me, and so I am still not sure what to believe... – gmoss Dec 17 '15 at 03:04
  • 2
    OK, one page above that, it says "Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown," so that explains that. Thanks everyone for your help. – gmoss Dec 17 '15 at 03:17

1 Answers1

2

The minimum sizes are:

  • char - 8-bit
  • short - 16-bit
  • int - 16-bit
  • long - 32-bit
  • long long - 64-bit

There are no maximum sizes, the compiler writer chooses whatever they think will work best for the target platform. The corresponding unsigned types have the same minimum size.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • Well, I should say, I believe you, even though as far as I can tell the standard declares that the *maximum* value of an unsigned long int is 2^32 - 1. But I'm probably looking at the wrong page or something... – gmoss Dec 17 '15 at 03:06
  • @gmoss the standard doesn't say that – M.M Dec 17 '15 at 03:10
  • 1
    OK, I found the phrase "Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown." Section 5.2.4.2.1, numbered pages 26-27 (pdf pages 45-46) of http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf. Thanks for your very quick help! – gmoss Dec 17 '15 at 03:16