On 10/17/2014 9:05 PM, Stefan Ram wrote:
>
pkon...@gmail.com writes:
>> Is there a way of allocating two large memory blocks next to
>> each other using 'new', 'malloc' or any other allocation
>> strategy?
>
> Round up both block sizes to account for all alignment
> requirements, then
>
> thetwoblockscanbefoundat = malloc( sizeoffirst + sizeoofsecond ).
>
>> The trick is that I want to use these two blocks as a single
>> memory space addressed by a pointer, though, later I'll
>> perform a two-fold in-place compression on such a vector and
>> I really have to release the upper half of the allocated
>> memory.
>
> thelowblockcouldstillbeat = realloc( thetwoblockscanbefoundat,
> sizeoffirst );
>
> C++ might not guarantee this, but your implementation might
> handle it this way.
>
expecting resizing in-place, and subsequent mallocs to allocate said
adjacent memory, is *very* unsafe and non-portable.
if applicable, possible is to just treat them as a single big block, for
example:
pBoth=malloc(szFirst+szSecond);
pFirst=pBoth;
pSecond=(void *)((char *)pBoth+szFirst); //*
*: while GCC and friends allow pointer arithmetic on 'void *', this is
an extension, and better is to cast to/from char or similar for the
arithmetic.
however, it is necessary to free both at the same time in this case.
as a practical example, this is commonly done with VBOs in OpenGL, since
generally you have to do everything in a given DrawArrays or
DrawArrayElements call with a single VBO bound (which is essentially a
memory buffer holding several parallel arrays).
or, in a particularly ugly example:
dumping most of the terrain geometry into a single massive set of
parallel arrays (generally holding around 1M vertices / 340k tris in
stats). as the player moves, the contents of these arrays are repacked
and uploaded to GL, mostly so that the terrain rendering could be cut
down to a more modest number of draw-calls.
so, say, one allocates 64MB for their temporary vertex arrays (using
mostly packed formats), fills them up, then copies some memory to
"collapse" any unused space, then sending the whole mess to GL.