lectures.alex.balgavy.eu

Lecture notes from university.
git clone git://git.alex.balgavy.eu/lectures.alex.balgavy.eu.git
Log | Files | Refs | Submodules

integer-overflows.md (1107B)


      1 +++
      2 title = 'Integer overflows'
      3 template = 'page-math.html'
      4 +++
      5 # Integer overflows
      6 Ints have a fixed size.
      7 
      8 For x86-64 Linux:
      9 
     10 <table>
     11 <tr><th>type</th><th>bits</th><th>min</th><th>max</th></tr>
     12 <tr><td>signed char</td><td>8</td><td>$-2^{7}$</td><td>$2^{7}-1$</td></tr>
     13 <tr><td>unsigned char</td><td>8</td><td>0</td><td>$2^{8}-1$</td></tr>
     14 <tr><td>short</td><td>16</td><td>$-2^{15}$</td><td>$2^{15}-1$</td></tr>
     15 <tr><td>unsigned short</td><td>16</td><td>0</td><td>$2^{16}-1$</td></tr>
     16 <tr><td>int</td><td>32</td><td>$-2^{31}$</td><td>$2^{31}-1$</td></tr>
     17 <tr><td>unsigned int</td><td>32</td><td>0</td><td>$2^{32}-1$</td></tr>
     18 <tr><td>long</td><td>64</td><td>$-2^{63}$</td><td>$2^{63}-1$</td></tr>
     19 <tr><td>unsigned long</td><td>64</td><td>0</td><td>$2^{64}-1$</td></tr>
     20 </table>
     21 
     22 If number doesn't fit, overflow. CPU discards bits that don't fit.
     23 i.e. result is computed modulo 2ⁿ (n = number of bits).
     24 
     25 leads to unexpected results in casts, computation, comparison:
     26 - truncation: cast to smaller type, discarding bits
     27 - arithmetic overflow: wrap around
     28 - signedness: negative int interpreted as unsigned