TITLE: Dealing with word alignment issues PROBLEM: changl@silver.cs.umanitoba.ca (Chang Li) I need to allocate a memory block with 8byte alignment? That is the block pointer is 8byte alignment. How can I do that with new? We can try this #define SIZE 62 p = new char[SIZE+7]; p = (char *)((((int)p+7)/8)*8); but if we delete [] p; there is memory leak. Are there any other methods to do this? RESPONSE: kanze@us-es.sel.de (James Kanze US/ESC 60/3/141 #40763), 10 Nov 94 The usual solution is to allocate a union: union X { char buf[ SIZE ] ; double forAlignment_double ; void* forAlignment_void_star ; long forAlingment_long ; } ; p = (new X).buf ; Actually, the *usual* solution is to just use malloc. RESPONSE: mfx@cs.tu-berlin.de (Markus Freericks) [ reply to CL ] First note: better use (long) instead of (int). Even then, it is not guaranteed that every implementation will do this right: sizeof(char*) might be bigger than sizeof(largest int). JK: For safety: void*, double and long. (I think that is enough. Does anyone know of a machine where it isn't?) MF: Second note: to get around the memory leak, encapsulate the pointer in an otherwise transparent class that holds the original, unaligned pointer. If you need the alignment a lot, better use a custom new() and a big, pre-allocated aligned array. JK: In the above, the address of X::buf is guaranteed to by the same as the address of the union. Formally, I think that you are supposed to cast the pointer back to the union type before delete; in practice, I cannot think of a conceivable implementation where this would be necessary. MF: Third note: it would be great if new() could take one more parameter, namely the alignment. I have sometimes need to access pages, and the abovementioned trick using is somewhat wasteful I want to align to 4096 byte ;-) Quite sad, since on many systems, the OS will allocate memory in pages anyway (say, brk() under UN*X). JK: New can take extra parameters. You just have to write the operator new yourself:-). Say to use brk directly. You will also have to provide your own delete (and thus, your own default new), with some means of distinguishing which memory is which.