Skip to content

Invalid optimization: clang makes invalid assumptions about malloc #114772

Open
@bhaible

Description

@bhaible

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

Metadata

Metadata

Labels

llvm:GVNGVN and NewGVN stages (Global value numbering)miscompilation

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions