I need to use a re-sizable buffer. For academic reasons I am not allowed to use realloc, not yet anyway, so I made a simple naive local implementation that simply uses malloc to allocate a new memory area of size n, and copies the bytes of the old buffer to it. Then frees the old memory, and returns a pointer to the newly created buffer.
I know this is far from optimal and causes memory fragmentation but it's all I can do for now.
I increase my buffer by calling my realloc and doubling it's size on each iteration. e.g I start with a buffer of 32 bytes, if I need more space, I call realloc and double that to 64 and so on.
The problem is that my realloc always crashes on the second call, right after trying to free the old memory.
Why could this be? I'd appreciate any help. Thanks
Code:
static void *my_realloc(void *mem, size_t size)
{
char *new_mem;
char *old_mem;
if (!mem || !size)
return ((void*)0);
new_mem = (char*)ft_memalloc(size * sizeof(char));
if (!new_mem)
return ((void*)0);
old_mem = mem;
while (*old_mem)
*new_mem++ = *old_mem++;
free(mem);
return (new_mem);
}
Crash occurs on free(mem), always on the second call.
To further illustrate, this is an example context of how I'm using the function:
Code:
....
const size_t buffer_size = 32;
char *buffer = (char*)malloc(buffer_size * sizeof(char) + 1);
while (...)
{
buffer = (char*)my_realloc(buffer, current_buff_size += buffer_size);
....
}