lua-users home
lua-l archive

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


Ralph Hempel wrote:
kathrin_69@gmx.de wrote:
Hi,

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.

<snip>

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?

And this expression  &(*mem)[0] is very strange. I parse that as:
std::vector<int> v;
int* c_array = &v[0]; //not just &v !

v.push_back(4);
v.push_back(2);

printf( "%d%d", c_array[0], c_array[1] ); //"42"

The expression gives the position of the continuous memory regions hold by std::vector. mem would just be the this-pointer of the vector object and therefore the wrong thing. This is an stl feature to get backward compatibility to c-style arrays as shown in the little example above.


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

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

Ralph


John had the right solution. I forgot to move the old mem to the new range in case of a re-allocation. Was my first allocator :)
Thank you all!