lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Ralph Hempel wrote: wrote:

I'm trying to replace the Lua default l_alloc function with my own one. My aim is to have all memory Lua allocates inside a single array of pre-allocated memory.


void* alloc_impl_manual( void* ptr, size_t osize, size_t nsize )
  if (nsize)
std::vector<unsigned char>* mem = new std::vector<unsigned char>(nsize);
               //yes, it will leak. don't care for now

return &(*mem)[0]; //returned memory position should be aligned by new
  return NULL;

Ummm, besides the leak, should you not be returning:

  return( mem )

since mem is already a pointer to the memory you allocated?

mem is a pointer to a "header", usually something like this:

class vector<T> {
  T *storage;
  size_t size; // Amount actually used
  size_t allocated; // number of elements in storage, >= size.

So, if you return mem, you're returning the address of that "header", not the array you've allocated.

And this expression  &(*mem)[0] is very strange. I parse that as:

(the adress of ( (the contents of mem) ???? )

my compiler warns that the subscripted value is neither an array nor a

vector overloads [] so that (*mem)[0] equals storage[0], which is exactly what you want the address of.