blob: 65c9274bfd14cf67553d5767f78c2e5275fe88c3 (
plain) (
blame)
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
|
// What the allocation tracker is for: a linked list of N nodes built and
// torn down, beside one of each other way to allocate.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
struct node *next;
long value;
};
int main(int argc, char **argv) {
long n = argc > 1 ? atol(argv[1]) : 100;
struct node *head = NULL;
for (long i = 0; i < n; i++) {
struct node *node = malloc(sizeof *node);
node->value = i;
node->next = head;
head = node;
}
// A vector that grows: realloc in place and realloc that moves.
size_t cap = 4, len = 0;
long *values = calloc(cap, sizeof *values);
for (struct node *node = head; node; node = node->next) {
if (len == cap) values = realloc(values, (cap *= 2) * sizeof *values);
values[len++] = node->value;
}
void *aligned = NULL;
if (posix_memalign(&aligned, 64, 100)) return 1;
void *page = aligned_alloc(4096, 4096);
memset(page, 1, 4096);
// Read through a volatile pointer: at -O1 the compiler otherwise knows
// the answer and deletes the allocation it came from.
volatile char *probe = page;
long sum = probe[100] - 1;
while (head) {
struct node *node = head;
head = node->next;
sum += node->value;
free(node);
}
free(values);
free(aligned);
free(page);
printf("sum %ld of %zu\n", sum, len);
return 0;
}
|