What is the default alignment of data/objects allocated by new?
Printable View
What is the default alignment of data/objects allocated by new?
At least 8 bytes. Most likely 16 or more. To really find out, you'd have to make some experiments or analyze the code that actually allocates memory. Just do somehting like this:
--Code:for(int i = 0; i < SOMELARGENUMBER; i++)
{
int x;
void *p = new char;
x = (int)p;
if (x & (4-1)) unalign4++;
if (x & (8-1)) unalign8++;
...
}
Mats
> What is the default alignment of data/objects allocated by new?
At least enough to support any of the native data types your compiler supports.
Anything else is way off into implementation specific territory.
As hinted above, you can write something like this:
However, as Salem explains, that is implementation dependent, and there is no guarantee that under some circumstances the alignment will be different from another time (e.g. it depends on what the allocation was before this allocation). But in gcc-mingw, the above example gives an output that shows that the only guaranteed alignment is 8. This may change if you use a different version of compiler/C library.Code:#include <stdio.h>
#include <stdlib.h>
typedef struct amap {
int alignmask;
char *name;
int count;
} amap;
#define T(x) { x-1, "Align" #x, 0 }
amap arr[] = {
T(4),
T(8),
T(16),
T(32),
T(64),
T(128),
T(256)
};
#define arrsize(a) (sizeof(a) / sizeof(a[0]))
int main()
{
int i;
int j;
for(i = 0; i < 100; i++)
{
char *p = malloc(32);
int v = (int) p;
for(j = 0; j < arrsize(arr)-1 && !(arr[j+1].alignmask & v); j++) ;
arr[j].count++;
}
for(i = 0; i < arrsize(arr); i++)
printf("%s: %d\n", arr[i].name, arr[i].count);
return 0;
}
--
Mats