I'm trying to code my own malloc. I generate a .so file and do some tests with my library. The basic allocation tests work and so does LD_PRELOAD=./libmy_malloc.so ls -laRH /. But when I run LD_PRELOAD=./libmy_malloc.so emacs, I get an error: emacs: Wrong type argument: characterp, -1.
Do you know what would be the cause of this one? I don't see where the mistake could be..
Here is the code I use for malloc / calloc / realloc / reallocarray and free :
Here is my struct :
typedef struct block_s
{
bool isFree;
void *_ptr;
size_t _size;
struct block_s *next;
} block_t;
extern block_t *_head;
#define _BLOCKSIZE_(size) (sizeof(block_t)+size)
malloc :
static size_t space_left = 0;
void *action(size_t size)
{
void *new = sbrk(size);
return (new == (void*)-1 ? NULL : new);
}
size_t getpage(size_t size)
{
size_t page = getpagesize() * 2;
while (page < _BLOCKSIZE_(size))
page += getpagesize() * 2;
return (page);
}
void *init_memblock(size_t size)
{
size_t tmp = getpage(size);
_head = action(tmp);
if (_head == NULL)
return (NULL);
space_left = tmp - _BLOCKSIZE_(size);
_head->isFree = false;
_head->_ptr = (char*)_head + sizeof(block_t);
_head->_size = size;
_head->next = NULL;
return (_head->_ptr);
}
void *alloc(size_t size, void *pos)
{
block_t *new = pos;
size_t page = getpage(size);
if (space_left < _BLOCKSIZE_(size)) {
if (action(page) == NULL)
return (NULL);
space_left += page;
}
space_left -= _BLOCKSIZE_(size);
new->isFree = false;
new->_ptr = (char*)new + sizeof(block_t);
new->_size = size;
new->next = NULL;
return (new);
}
block_t *search_memblock(block_t *_block, size_t size)
{
block_t *prev = NULL;
while (_block != NULL) {
prev = _block;
if (_block->isFree == true && _block->_size >= size) {
_block->isFree = false;
return (_block);
}
_block = _block->next;
}
prev->next = alloc(size, (void*)prev+_BLOCKSIZE_(prev->_size));
return (prev->next);
}
void *malloc(size_t size)
{
block_t *memblock = NULL;
if (!size)
return (NULL);
if (_head == NULL)
return (init_memblock(size));
memblock = search_memblock(_head, size);
if (memblock != NULL)
return (memblock->_ptr);
return (NULL);
}
free :
void free(void *ptr)
{
block_t *block = ptr - sizeof(block_t);
if (!ptr)
return;
block->isFree = true;
}
calloc :
void *calloc(size_t nmemb, size_t size)
{
void *ptr = malloc(nmemb * size);
if (ptr == NULL)
return (NULL);
memset(ptr, 0, nmemb * size);
return (ptr);
}
realloc :
void *realloc(void *ptr, size_t size)
{
void *tmp = NULL;
if (size == 0) {
free(ptr);
return (NULL);
}
if (ptr == NULL)
return (malloc(size));
tmp = malloc(size);
if (tmp)
memcpy(tmp, ptr, size);
if (ptr)
free(ptr);
return (tmp);
}
and reallocarray :
void *reallocarray(void *ptr, size_t nmemb, size_t size)
{
return (realloc(ptr, nmemb * size));
}
Thank you in advance