Create and resize dynamic array without C libraries? -
is there way create dynamic arrays in c without having utilize stdlib?
malloc
requires stdlib.h
library, not allowed utilize in project.
if has ideas, please share? thanks.
malloc
not just library, way interface operating scheme inquire more memory running process. well, inquire more memory , manage free/occupied memory yourself, wrong on many levels.
but, inclined believe project going run in kind of platform not have operating system, it?1 in case, faster solution first allocate statically memory in big global array, , every time need memory inquire manager responsible big array.
let me give example, sake of simplicity tiny , not functional, quick start.
typedef char bool; #define block_size 1024 //each allocation must have in max 1kb #define max_data 1024*1024*10 //our programme statically allocates 10mb #define blocks (max_data/block_size) typedef char scott_block[block_size]; scott_block scott_memory[blocks]; bool scott_used_memory[blocks]; void* scott_malloc(unsigned size) { if( size > block_size ) homecoming null; unsigned int i; for(i=0;i<blocks;++i) { if( scott_used_memory[i] == 0 ) { scott_used_memory[i] = 1; homecoming scott_memory[i]; } } homecoming null; } void scott_free(void* ptr) { unsigned int pos = ((char*)(ptr)-scott_memory[0])/block_size; printf("pos %d\n",pos); scott_used_memory[pos] = 0; }
i wrote code show how emulate memory manager. allow me point out few improvements may done it.
first, scott_used_memory bitmap instead of bool
array. second, not allocate memory bigger block_size, should search consecutives blocks create bigger block. need more command info tell how much blocks allocated void*
occupies. third, way free memory searched (linearly) slow, blocks creates link list of free blocks.
but, said, great quick start. , depending on needs may fulfill well.
1 if not, have absolutely no reason not utilize malloc.
c arrays dynamic malloc
No comments:
Post a Comment