c - custom memory allocator -
i wrote custom memory allocator. has 2 restrictions want remove works malloc/free.
1.) mem_free call requires cast unsigned char * input parameter. take pointer of type. how can done?
2.) memory allocator wrote allocates block of memory front of buffer , writes size. free function removes last block of allocated memory in buffer. order of malloc/free calls matter or not work. how can remove restriction?
want able this:
char* ptr1 = mem_alloc(10); char* ptr2 = mem_alloc(4); mem_free(ptr1); mem_free(ptr2); have now:
char* ptr1 = mem_alloc(10); char* ptr2 = mem_alloc(4); mem_free(ptr2); mem_free(ptr1); code:
unsigned char* mem_alloc(unsigned int size) { unsigned int s; if( (size + mem_header_size) > (mem_max_size - mem_current_size_bytes) ) { return null; } if(is_big_endian() == 0) { s = (mem_buff[3] << 24) + (mem_buff[2] << 16) + (mem_buff[1] << 8) + mem_buff[0]; } else { s = (mem_buff[0] << 24) + (mem_buff[1] << 16) + (mem_buff[2] << 8) + mem_buff[3]; } memcpy(mem_buff + mem_current_size_bytes, &size, sizeof(unsigned int)); unsigned char* result = mem_buff + (mem_current_size_bytes + mem_header_size); mem_current_size_bytes += mem_header_size + size; return result; } void mem_free(unsigned char* ptr) { unsigned int i,s; for(i=0; i<mem_current_size_bytes; i++) { if( (char*)ptr == (char*)(mem_buff + i) ) { if(is_big_endian() == 0) { s = (*(ptr - 1) << 24) + (*(ptr - 2) << 16) + (*(ptr - 3) << 8) + *(ptr - 4); } else { s = (*(ptr - 4) << 24) + (*(ptr - 3) << 16) + (*(ptr - 2) << 8) + *(ptr - 1); } mem_current_size_bytes-=s; mem_current_size_bytes-=mem_header_size; break; } } }
1) use void* instead.
2) store map of addresses allocated blocks , seperate map of unallocated blocks. can block being freed in allocated map, remove , add block unallocated map (making sure merge free blocks either side of it). of course, can , lead memory fragmentation rather unavoidable really.
Comments
Post a Comment