<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/114772>114772</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            Invalid optimization: clang makes invalid assumptions about malloc
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          bhaible
      </td>
    </tr>
</table>

<pre>
    When optimizing, clang apparently assumes that a `malloc` invocation does not change `errno`. This assumption is wrong: on all platforms, `malloc` sets `errno` (usually to `ENOMEM`) when it returns NULL.

**How to reproduce:**

Save this as foo.c.
```
#include <stdlib.h> /* malloc */
#include <errno.h> /* errno */
#include <stdio.h> /* printf */
#include <stdint.h> /* SIZE_MAX */

int
main ()
{
 errno = 0;
  void *volatile p = malloc (SIZE_MAX / 10);
  int err = errno;
  printf ("errno=%d\n", err);
}
```
Then:
```
$ clang -O2 foo.c && ./a.out
errno=0
$ clang foo.c && ./a.out
errno=12
```
```
$ clang --version
clang version 19.1.0 (/home/runner/work/llvm-project/llvm-project/clang a4bf6cd7cfb1a1421ba92bca9d017b49936c55e4)
Target: x86_64-unknown-linux-gnu
Thread model: posix
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyMVF9vpDYQ_zTmZbQI2_x94CGXBPWky93DpWrVl5PBBtwYG9lmN-mnrwxsstuk7UnIMjPzm38_zzDn5KCFqFH2CWV3EVv8aGzdjky2SkSt4S_1b6PQYGYvJ_mX1AMit9Appgdg88ys0F69AHNumYQDPzIPDFCeTEwp06E8AamPpmNeGg3cCAfaeOhGpgcR7IS12qA8ieFxlG5zNK_G0sHJGj0gegNGA1MKZsV8b-zkQhJXQZzw7tIdIFIubmFKvYA3QXP_9dvD_QPKE0QqOIWapAcr_GK1g6-_fvkSo-QOJTf7ScL3izkFtBWzNXzpBKK74tL0OzsK8Fvy0BsTd2dPebJ_u0sqdacWLgDRW-e5km08InoPiDSI3MBWDawRmo8wa3FXkFXyHwjnubxGzFZq3_8PRPsrzPfPf9z_eLj5_Rq1nlL77TIxqUPTEal2ffFpu5yTpHeQIHoWwtFIHhwejWJeKgHzavLahPIiagM40HaBltoHvytk4_xN91piiQjZlXeIZBxltxoREh6PsPbSISruPuTscRQ6kP4xn-k-CIdvZCMeEMkRySFGpGGxWfbenHN4B_wZECYfR__XZA5HYZ00elNswl0EuIpxnGytaUYzCUQau2gtLCLNydgnRBqljtNhtuZP0fn3v_vop22fd7zo-hYznBLcsoq0Hat4gos2rSqad1km0tfX8MjsIHwY5ecy_5Gnh0U_aXPSByX18nwY9HJuuBWMw2S4UMF6Nk4-_6PiiNeUV7RikahxQZMC51lForEuOM1KjgWhfSl6zDDFOSUZ7UtSlllfRbImCUkxTlKc0JySmFZFSnCRsq7FLec9ShMxManiUHVs7BBJ5xZRY5wWBYkUa4Vy52Vp67U37TI4lCZKOu_ecF56JerP-siU5Of1uW7BUNbWxYk9CRf242rztvocsNYsfp-FaLGqHr2f3bp-GkSaQfpxaePOTDtB73la83aINHvqx5r8HQAA___qobyF">