[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Lua alloc function with just malloc and free causes crash
- From: ramsdell@... (John D. Ramsdell)
- Date: 05 Aug 2006 10:16:47 -0400
I'm using Lua 5.1.1 in an environment that provides only malloc and
free. Initially, I wrote my Lua allocator so that whenever Lua
requested that the size of an object be reduced, it simply returned
the object unaltered. This allocator works well.
Today, I tried to allow Lua to better compact its memory usage by
allocating a reduced sized copy of an object when Lua requests that
the size of an object be reduced, and then freeing the original. This
version of the allocator causes a horrible crash.
The Lua documentation states that Lua assumes that the allocator never
fails when osize >= nsize. Does Lua also assume that the following
expression always evaluates to true when osize >= nsize?
ptr == my_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
If so, please update the documentation. If not, I'll start debugging
the implementation of malloc and free I'm using. Thanks in advance.
John
#include <stddef.h>
#include <string.h>
void *malloc(size_t size);
void free(void *ptr);
void *my_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
{
if (nsize == 0) {
free(ptr);
return NULL;
}
else if (ptr == NULL)
return malloc(nsize);
#if defined COMPACT
else if (osize == nsize) {
return ptr;
else if (osize > nsize) {
void *p = malloc(nsize);
if (p == NULL)
return ptr;
memcpy(p, ptr, osize);
free(ptr);
return p;
}
#else
else if (osize >= nsize)
return ptr;
#endif
else {
void *p = malloc(nsize);
if (p == NULL)
return p;
memcpy(p, ptr, osize);
free(ptr);
return p;
}
}