Revisiting Two Examples of Undefined Behavior

Martin Uecker, 2025-09-29


I recently revisited an old (2012) post by John Regehr about undefined behavior, which highlights the following two examples. It turns out that GCC can nowadays warn about both, at least in these simple cases. (Clang, sadly, does not.)

Example 1:

enum {N = 32};
int a[N], pfx[N];
void prefix_sum (void)
{
  int i, accum;
  for (i = 0, accum = a[0]; i < N; i++, accum += a[i])
    pfx[i] = accum;
}
	
Godbolt


	: In function 'prefix_sum':
:9:51: warning: iteration 31 invokes undefined behavior [-Waggressive-loop-optimizations]
    9 |   for (i = 0, accum = a[0]; i < N; i++, accum += a[i])
      |                                                  ~^~~
:9:31: note: within this loop
    9 |   for (i = 0, accum = a[0]; i < N; i++, accum += a[i])
      |                             ~~^~~
	

Example 2:


#include <stdio.h>
#include <stdlib.h>

int main() {
  int *p = malloc(sizeof(int));
  int *q = realloc(p, sizeof(int));
  *p = 1;
  *q = 2;
  if (p == q)
    printf("%d %d\n", *p, *q);
}
	


:11:5: warning: pointer 'p' may be used after 'realloc' [-Wuse-after-free]
   11 |     printf("%d %d\n", *p, *q);
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~
:7:12: note: call to 'realloc' here
    7 |   int *q = realloc(p, sizeof(int));
      |            ^~~~~~~~~~~~~~~~~~~~~~~
:8:6: warning: pointer 'p' used after 'realloc' [-Wuse-after-free]
    8 |   *p = 1;
      |   ~~~^~~
:7:12: note: call to 'realloc' here
    7 |   int *q = realloc(p, sizeof(int));
      |            ^~~~~~~~~~~~~~~~~~~~~~~
	

Godbolt

References