aboutsummaryrefslogtreecommitdiff
path: root/lang/c/counted_by.c
blob: 09d46996999cf0eacce73a3c34558141e1285496 (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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#define _GNU_SOURCE

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

struct foo {
	uint64_t a;
	uint64_t b;
};

struct bounded_flex_t {
	uint64_t count;

	// NOTE: try to move this member somewhere else and you will get:
	//   counted_by.c:13:20: error: flexible array member not at end of struct
	struct foo flex_array[] __attribute__((counted_by(count)));
};

void free_flex(struct bounded_flex_t **flex)
{
	struct bounded_flex_t *ptr = *flex;

	printf("Freeing a flexible array of %ld members.\n", ptr->count);
	free(*flex);
}

__attribute__((noreturn)) void die(const char *const str)
{
	fprintf(stderr, str);
	exit(EXIT_FAILURE);
}

int main(int argc, char *argv[])
{
	uint64_t len = 1;

	if (argc == 2) {
		len = (uint64_t) strtol(argv[1], NULL, 10);
		if (!len) {
			die("error: bad integer value!\n");
		}
	} else if (argc > 2) {
		die("error: only pass one argument maximum!\n");
	}

	// That's a mouthful :P
	struct bounded_flex_t *flex __attribute__((cleanup(free_flex))) = malloc(sizeof(struct bounded_flex_t) + (len * sizeof(struct foo)));
	if (!flex) {
		die("error: could not allocate memory for it");
	}

	// NOTE: if this is not the first thing that we do, and we use 'len' for the
	// for loop below, then we will get a runtime error from the array bound
	// checker. Hence, pretty much like in Rust :)
	flex->count = len;

	uint64_t accumulator = 0;
	for (uint64_t i = 0; i < flex->count; i++) {
		flex->flex_array[i] = (struct foo){ .a = accumulator, .b = accumulator + 1};
		accumulator++;
	}

	for (uint64_t i = 0; i < flex->count; i++) {
		printf("%ld: .a = %ld, .b = %ld\n", i, flex->flex_array[i].a, flex->flex_array[i].b);
	}
}