NetBurner 3.5.6
PDF Version
memoryAllocator.h
1#ifndef _MEMORY_ALLOCATOR_H_
2#define _MEMORY_ALLOCATOR_H_
3
4#include <stdint.h>
5#include <predef.h>
6
7/* C Standard Library */
8#include <ctype.h>
9#include <malloc.h>
10#include <stdio.h>
11
12/* Portability & uCos Definitions */
13#include <basictypes.h>
14#include <nbrtos.h>
15#include <nbrtoscpu.h>
16
17/* NB Runtime Libraries */
18#include <constants.h>
19
20#ifdef __cplusplus
21class MemoryAllocator
22{
23 public:
24 virtual void *allocate(size_t size) = 0;
25 virtual void deallocate(void *ptr) = 0;
26 virtual void *reallocate(void *ptr, size_t size) = 0;
27 virtual ~MemoryAllocator() {}
28};
29
30class BlockMemoryAllocator : public MemoryAllocator
31{
32 public:
33 BlockMemoryAllocator(void *pMemory, size_t memorySize, size_t blockSize);
34 ~BlockMemoryAllocator() override;
35 void *allocate(size_t size) override;
36 void deallocate(void *ptr) override;
37 void *reallocate(void *ptr, size_t size) override;
38
39 void printStats() const;
40 private:
41 struct Block
42 {
43 Block *prev;
44 Block *next;
45 bool free;
46 };
47 void *_pMemory;
48 size_t _memorySize;
49 OS_CRIT m_critSec;
50 Block *_pBlockList;
51 size_t _blockSizeMultiplier; // All blocks are a multiple of this size
52
53 const size_t largestSizeToAllocate = 10560;
54
55 // Profiling data
56 size_t _numAllocations;
57 size_t _numDeallocations;
58 size_t _numOOMAllocations;
59 size_t _numToLargeAllocations;
60 size_t _allocatedMemory;
61
62 size_t getBlockSize(Block *pBlock) const;
63 size_t getAlignedBlockSize(size_t size) const;
64 Block *getBlockFromPointer(void *pBlock) const;
65 void splitBlock(Block *pBlock, size_t size);
66 void coalesceBlocks(Block *pBlock);
67
68};
69
70#define CREATE_MEMORY_ALLOCATOR_SRAM(name, memorySize) \
71 alignas(4) static uint8_t memoryBuffer##name[memorySize] FAST_USER_VAR; \
72 BlockMemoryAllocator name(memoryBuffer##name, memorySize, 32)
73
74#define CREATE_MEMORY_ALLOCATOR_TCM(name, memorySize) \
75 alignas(4) static uint8_t memoryBuffer##name[memorySize] FAST_SYS_VAR; \
76 BlockMemoryAllocator name(memoryBuffer##name, memorySize, 32)
77
78#define CREATE_MEMORY_ALLOCATOR_SDRAM(name, memorySize) \
79 alignas(4) static uint8_t memoryBuffer##name[memorySize]; \
80 BlockMemoryAllocator name(memoryBuffer##name, memorySize, 32)
81
82#endif
83#endif // _MEMORY_ALLOCATOR_H_
NetBurner System Constants.
NetBurner Real-Time Operating System (NBRTOS) API.
An OS_CRIT object is used to establish critical sections of code that can only be run by one task at ...
Definition nbrtos.h:1110