1 /*
2 * Copyright (c) 2022 Jeppe Odgaard
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/kernel.h>
8 #include <zephyr/sys/sys_heap.h>
9
10 #define HEAP_SIZE 256
11
12 static char heap_mem[HEAP_SIZE];
13 static struct sys_heap heap;
14
15 static void print_sys_memory_stats(void);
16
main(void)17 int main(void)
18 {
19 void *p;
20
21 printk("System heap sample\n\n");
22
23 sys_heap_init(&heap, heap_mem, HEAP_SIZE);
24 print_sys_memory_stats();
25
26 p = sys_heap_alloc(&heap, 150);
27 print_sys_memory_stats();
28
29 p = sys_heap_realloc(&heap, p, 100);
30 print_sys_memory_stats();
31
32 sys_heap_free(&heap, p);
33 print_sys_memory_stats();
34 return 0;
35 }
36
print_sys_memory_stats(void)37 static void print_sys_memory_stats(void)
38 {
39 struct sys_memory_stats stats;
40
41 sys_heap_runtime_stats_get(&heap, &stats);
42
43 printk("allocated %zu, free %zu, max allocated %zu, heap size %u\n",
44 stats.allocated_bytes, stats.free_bytes,
45 stats.max_allocated_bytes, HEAP_SIZE);
46 }
47