File: unaligned-write.c

package info (click to toggle)
gcc-sh-elf 8.3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 140 kB
  • sloc: ansic: 237; makefile: 93; sh: 54
file content (32 lines) | stat: -rw-r--r-- 1,152 bytes parent folder | download | duplicates (2)
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
/* SPDX-FileCopyrightText: 2021 John Scott <jscott@posteo.net>
 * SPDX-License-Identifier: GPL-3.0-or-later */
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
	/* Pointers to void and pointers to char are required to have
	 * the same representation per the ISO C standard. Here we
	 * do a crude check that pointers to int probably also have the
	 * same representation. This in general is not a good assumption
	 * to make, but this is sufficient to justify our type-punning later. */
	static_assert(sizeof(char*) == sizeof(void*), "this ABI does not conform to the ISO C standard");
	static_assert(sizeof(char*) == sizeof(int*), "pointers to char and pointers to int do not have the same representation");
	int test_int;
	int *test_i = &test_int;
	char *test_c = (void*)&test_int;
	if(memcmp(&test_i, &test_c, sizeof(void*))) {
		fputs("Pointers to char and pointers to int do not have the same representation\n", stderr);
		exit(EXIT_FAILURE);
	}

	int integers[2];
	union {
		int *i;
		char *c;
	} pointers = { .i = integers };
	pointers.c++;
	/* i is now unsuitably aligned */
	*pointers.i = 0;
}