← Back to davo.co
summaryrefslogtreecommitdiffstats
path: root/crash.c
blob: 3a99d9e699fcb1b5313bb9a35262d3e16c8c4144 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "c23-fallback.h"
#include <stdio.h>
#include <stdalign.h>
#include <inttypes.h>
#include <complex.h>
#include "crash.h"

void enable_alignment_check(void);
typedef complex double cdbl;

int main(void) {
  enable_alignment_check();
  /* An overlay of complex values and bytes. */
  union {
    cdbl val[2];
    unsigned char buf[sizeof(cdbl[2])];
  } toocomplex = {
    .val = { 0.5 + 0.5*I, 0.75 + 0.75*I, },
  };
  printf("size/alignment: %zu/%zu\n",
         sizeof(cdbl), alignof(cdbl));
  /* Run over all offsets, and crash on misalignment. */
  for (size_t offset = sizeof(cdbl); offset; offset /=2) {
    printf("offset\t%zu:\t", offset);
    fflush(stdout);
    cdbl* bp = (cdbl*)(&toocomplex.buf[offset]); // align!
    printf("%g\t+%gI\t", creal(*bp), cimag(*bp));
    fflush(stdout);
    *bp *= *bp;
    printf("%g\t+%gI", creal(*bp), cimag(*bp));
    fputc('\n', stdout);
  }
}