473,465 Members | 2,092 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

memory allocators & proper alignment...

Here is some info on a C++ allocator prototype I am working on:

http://groups.google.com/group/comp....eee1f61fdbb52c

Any tried-and-true techniques for calculating the correct alignment of any
C++ type the user can throw at it? For the initial code, I was assuming that
the alignment(T) == sizeof(T)... Now that I am so close to being able to
release this thing, I wanted to be able to stitch up this loose end.

All of the allocators I have worked on were always uses by entities which
were private to a library implementation... Any they only needed to align
structures on level-2 cache-line boundaries. So, I didn't need to align for
the type, I only align for the cache line.

Now I need to figure out how to get the correct alignment of any C++ type a
user can come up with...

Help!
:^)

--
Chris M. Thomasson
http://appcore.home.comcast.net

May 16 '07 #1
13 3591
"Chris Thomasson" <cr*****@comcast.netwrote in message
news:mJ******************************@comcast.com. ..
Here is some info on a C++ allocator prototype I am working on:

http://groups.google.com/group/comp....eee1f61fdbb52c
[...]
Now I need to figure out how to get the correct alignment of any C++ type
a user can come up with...
I think I will just go ahead and post the code today or tomorrow.

May 17 '07 #2
Chris Thomasson wrote:
Here is some info on a C++ allocator prototype I am working on:

http://groups.google.com/group/comp....eee1f61fdbb52c
Any tried-and-true techniques for calculating the correct alignment of
any C++ type the user can throw at it? For the initial code, I was
assuming that the alignment(T) == sizeof(T)... Now that I am so close to
being able to release this thing, I wanted to be able to stitch up this
loose end.

All of the allocators I have worked on were always uses by entities
which were private to a library implementation... Any they only needed
to align structures on level-2 cache-line boundaries. So, I didn't need
to align for the type, I only align for the cache line.

Now I need to figure out how to get the correct alignment of any C++
type a user can come up with...

Help!
:^)
There is no infallible way to compute that in standard C++. I recall
reading about techniques that almost always work. This article seems to
describe one of those (although it doesn't ring any bells for me).

http://www.monkeyspeak.com/alignment/

john
May 17 '07 #3
On May 17, 11:02 am, "Chris Thomasson" <cris...@comcast.netwrote:
"Chris Thomasson" <cris...@comcast.netwrote in message

news:mJ******************************@comcast.com. ..
Here is some info on a C++ allocator prototype I am working on:
http://groups.google.com/group/comp..../thread/beeee1...

[...]
Now I need to figure out how to get the correct alignment of any C++ type
a user can come up with...
one way:
template <typename T>
struct alignof_static
{
struct Helper1 { T v; };
struct Helper2 { char c; Helper1 v; };

static const unsigned value = sizeof(Helper2)-sizeof(Helper1);
};
template <typename T>
unsigned alignof()
{
return alignof_static<T>::value;
}

#ifdef __GNUC__
struct X
{
int a;
} __attribute__ ((aligned (8)));
#else
typedef int X;
#endif
#include <iostream>
int main()
{
std::cout << alignof<char>() << "\n";
std::cout << alignof<short>() << "\n";
std::cout << alignof<int &>() << "\n";
std::cout << alignof<char &>() << "\n";
std::cout << alignof<X>() << "\n";
}

May 17 '07 #4
On May 17, 11:02 am, "Chris Thomasson" <cris...@comcast.netwrote:
"Chris Thomasson" <cris...@comcast.netwrote in message

news:mJ******************************@comcast.com. ..
Here is some info on a C++ allocator prototype I am working on:
http://groups.google.com/group/comp..../thread/beeee1...

[...]
Now I need to figure out how to get the correct alignment of any C++ type
a user can come up with...

I think I will just go ahead and post the code today or tomorrow.
I'm not sure why my previous attempt at posting this didn't show up -
if this is a second post - apologies in advance.

template <typename T>
struct alignof_static
{
struct Helper1 { T v; };
struct Helper2 { char c; Helper1 v; };

static const unsigned value = sizeof(Helper2)-sizeof(Helper1);
};
template <typename T>
unsigned alignof()
{
return alignof_static<T>::value;
}

#ifdef __GNUC__
struct X
{
int a;
} __attribute__ ((aligned (8)));
#else
typedef int X;
#endif
#include <iostream>
int main()
{
std::cout << alignof<char>() << "\n";
std::cout << alignof<short>() << "\n";
std::cout << alignof<int &>() << "\n";
std::cout << alignof<char &>() << "\n";
std::cout << alignof<X>() << "\n";
}
May 17 '07 #5
On May 17, 11:34 am, Gianni Mariani <gi3nos...@mariani.wswrote:
On May 17, 11:02 am, "Chris Thomasson" <cris...@comcast.netwrote:
"Chris Thomasson" <cris...@comcast.netwrote in message
news:mJ******************************@comcast.com. ..
Here is some info on a C++ allocator prototype I am working on:
>http://groups.google.com/group/comp..../thread/beeee1....
[...]
Now I need to figure out how to get the correct alignment
of any C++ type a user can come up with...
one way:
template <typename T>
struct alignof_static
{
struct Helper1 { T v; };
struct Helper2 { char c; Helper1 v; };
static const unsigned value = sizeof(Helper2)-sizeof(Helper1);
Just curious, but why Helper1? I would have expected:

struct Helper { char c; T v ; } ;
static const size_t value = sizeof( Helper ) - sizeof( T ) ;

Word addressed machines will typically require all struct's to
be aligned at word boundaries; only character types are exempt
from the requirement. But since the above seems so obvious, I
presume that there is some reason I haven't seen for not using
it.

--
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 17 '07 #6
James Kanze wrote:
On May 17, 11:34 am, Gianni Mariani <gi3nos...@mariani.wswrote:
>On May 17, 11:02 am, "Chris Thomasson" <cris...@comcast.netwrote:
>>"Chris Thomasson" <cris...@comcast.netwrote in message
>>news:mJ******************************@comcast.co m...
>>>Here is some info on a C++ allocator prototype I am working on:
>>>http://groups.google.com/group/comp..../thread/beeee1...
>>[...]
Now I need to figure out how to get the correct alignment
of any C++ type a user can come up with...
>one way:
template <typename T>
struct alignof_static
{
struct Helper1 { T v; };
struct Helper2 { char c; Helper1 v; };
static const unsigned value = sizeof(Helper2)-sizeof(Helper1);

Just curious, but why Helper1? I would have expected:

struct Helper { char c; T v ; } ;
static const size_t value = sizeof( Helper ) - sizeof( T ) ;
Think about what the expression above does when T = char &.

I attached another version which has two alignof methods - one for
dealing with the reference as a type and the other to deal with the
references and the underlying type as the same.
>
Word addressed machines will typically require all struct's to
be aligned at word boundaries; only character types are exempt
from the requirement. But since the above seems so obvious, I
presume that there is some reason I haven't seen for not using
it.
You can probably do a static assert for this - i.e. safe since it fails
to compile on platforms that don't support it.

template <typename T>
struct noreference
{
typedef T type;
};

template <typename T>
struct noreference<T&>
{
typedef T type;
};

template <typename T>
struct alignof_static
{
struct Helper1 { T v; };
struct Helper2 { char c; Helper1 v; };

static const unsigned value = sizeof(Helper2)-sizeof(Helper1);
};

template <typename T>
struct alignof_noref_static
{
static const unsigned value = alignof_static<typename noreference<T>::type >::value;
};

template <typename T>
unsigned alignof()
{
return alignof_static<T>::value;
}

template <typename T>
unsigned alignof_noref()
{
return alignof_noref_static<T>::value;
}

#ifdef __GNUC__
struct X
{
int a;
} __attribute__ ((aligned (8)));
#else
typedef int X;
#endif
#include <iostream>
int main()
{
std::cout << alignof<char>() << "\n";
std::cout << alignof<short>() << "\n";
std::cout << alignof<int &>() << "\n";
std::cout << alignof<char &>() << " noref=" << alignof_noref<char &>() << "\n";
std::cout << alignof<X>() << "\n";
}

May 18 '07 #7
Gianni Mariani wrote:
James Kanze wrote:
....

I forgot to mention - I decided to switch news servers after my last
response didn't show for a few hours. So apologies again for double posts.
May 18 '07 #8
Gianni Mariani wrote:
James Kanze wrote:
On May 17, 11:34 am, Gianni Mariani <gi3nos...@mariani.wswrote:
On May 17, 11:02 am, "Chris Thomasson" <cris...@comcast.netwrote:
[...]
Now I need to figure out how to get the correct alignment
of any C++ type a user can come up with...
one way:
template <typename T>
struct alignof_static
{
struct Helper1 { T v; };
struct Helper2 { char c; Helper1 v; };
static const unsigned value = sizeof(Helper2)-sizeof(Helper1);
Just curious, but why Helper1? I would have expected:
struct Helper { char c; T v ; } ;
static const size_t value = sizeof( Helper ) - sizeof( T ) ;
Think about what the expression above does when T = char &.
Bingo. That's what I hadn't thought of.

I'm not sure that it's all that useful to ask the alignment of
something that the standard says might not occupy memory:-). On
the other hand, for most people, the case is probably more
likely to occur in practice that is the case of a word addressed
machine (unless you're a mainframes programmer, and your company
buys from Unisys). A good library should probably handle both
(i.e. word addressed machines, and the alignment of references)
correctly.

(The simplest solution would probably be to use both techniques,
forcing an error if the results weren't equal. That would
probably handle 99% of the cases, and would cause a compile time
error for the cases it didn't handle. Otherwise, I think that
it should be possible to use some metaprogramming tricks to use
one technique for references, and the other otherwise.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 18 '07 #9
Thank you all for your time and energy!

Humm... This thread might be of interest to this group. I say this simply
because current C++ has no concept of threads... I can allow you to create a
single-threaded allocator in C++, and transform it into a full-blown
scaleable mulit-threaded one:

http://groups.google.com/group/comp....87f9cb2cb62d84
No kidding!
So, all of your single threaded C++ allocators can be transformed into
multi-threaded versions, simply by applying a simple lock-free algorithm I
invented.
Any thoughts? Could the technology/method I invented be of use to you or
your company?
May 21 '07 #10
Here is the caveat!

I need to be able to create an instance of your single-threaded allocator by
using extern "C" Create/Destroy function pointers.

May 21 '07 #11
Here is some updated rough-example code:

http://appcore.home.comcast.net/vzoo...oc/example.cpp
Notice any problems right off the bat?

May 22 '07 #12
One more quick question...

wrt overloading global new and delete operators...

struct alignchar {
char m_buf;
};

void* ::operator new(size_t sz) {
// alloc and align buf on sizeof(alignchar) boundary
char* const buf = ::mymalloc_aligned(sz, sizeof(alignchar));
if (! buf) { throw std::bad_alloc(); }
return buf ;
}

void ::operator delete(void *buf) {
::myfree(buf);
}
Is that sufficient alignment? AFAICT, void* ::operator new(size_t) does not
have to align for the specific C++ type... It just has to mimic malloc
alignment requirements right?

And, the size variable (e.g., size_t sz) passed to the void* ::operator
new(size_t) function when new is called with any type should be large enough
to accommodate the alignment for those types?
Thanks.
May 22 '07 #13
On May 22, 8:14 pm, "Chris Thomasson" <cris...@comcast.netwrote:
One more quick question...
wrt overloading global new and delete operators...
struct alignchar {
char m_buf;
};
Not sure what you're trying to achieve here, but on all of the
platforms I have access to, sizeof( alignchar ) is 1. About the
only cases where I would expect something different would be on
a word addressed machine.
void* ::operator new(size_t sz) {
// alloc and align buf on sizeof(alignchar) boundary
char* const buf = ::mymalloc_aligned(sz, sizeof(alignchar));
if (! buf) { throw std::bad_alloc(); }
return buf ;
}
void ::operator delete(void *buf) {
::myfree(buf);
}
Is that sufficient alignment? AFAICT, void* ::operator new(size_t) does not
have to align for the specific C++ type... It just has to mimic malloc
alignment requirements right?
The returned address should be sufficiently aligned for any data
type. Just like malloc, yes.
And, the size variable (e.g., size_t sz) passed to the void* ::operator
new(size_t) function when new is called with any type should be large enough
to accommodate the alignment for those types?
Run that by me again. There's no relationship between the size
argument and the alignment requirements for operator new.
Although logically... my machine requires an alignment of 8 for
double, but it doesn't make much sense to require operator
new(4) to return memory aligned on an 8 byte boundary, because
there's no way you can write anything larger than a float or an
int into the returned memory, and they only require an alignment
of 4. But the requirement in the standard (§3.7.3.1) is clear:
"The pointer returned shall be suitably aligned so that it can
be converted to a pointer of any complete object type and then
used to access the object or array in the storage allocated."
"Any complete object type", and not "Any complete object type
which will fit in the allocated memory".

The usual way to determine alignment of a type T, I believe, is
something like:

struct AlignOfT { char a ; T b ; } ;
size_t alignOfT() { return offsetof( AlignOfT, b ) ; }

(This only works for POD types, of course.)

If you want to ensure alignment for any possible type, use a
union of all the basic types, plus a few pointers (to char, to a
struct, to a function, etc.) for T in the above. It's not
formally guaranteed by the standard, but it should work on any
real platform.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 23 '07 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
by: Tron Thomas | last post by:
Given the following information about memory management in C++: ----- The c-runtime dynamic memory manager (and most other commercial memory managers) has issues with fragmentation similar to a...
11
by: aaaaa | last post by:
Hi all, Does anybody know if STLPort or SGI STL standard allocators do memory pooling for the list, map and set? Also I have had a look at the BOOST pool_alloc (to be used as a pooling...
6
by: Ares Lagae | last post by:
Hello, I am trying to create a container the stl way, and I have a couple of questions. The code of the container in question can be found at ...
13
by: sachin_mzn | last post by:
Hi, What is the concept of memory alignment? Is memory alignment differs, If a data type is local to a function or if it is a member of structure or union? How 32 to 64 bit processor afftects the...
29
by: K. Jennings | last post by:
I would like to get the result of malloc() such that it is aligned on a given boundary - 8, in this case. Assuming that sizeof(u64) is 8, will u64 *p = malloc(N) ; do the trick in general? ...
3
by: yasmin | last post by:
I am dealing with internal memory fragmentation issues in my program (C++ program on freeBSD). It involves a large number of fixed-size structures. For example for my records which are typically...
2
by: somenath | last post by:
Hi All, I have one question regarding the alignment of pointer returned by malloc. In K&R2 page number 186 one union is used to enforce the alignment as mentioned bellow. typedef long...
31
by: Chris Thomasson | last post by:
How many C compilers provide extensions which allow for a standard implementation of the following hack? ____________________________________________________________________ #include <stdio.h> ...
12
by: David Given | last post by:
I have a situation where I need to be able to allocate chunks on unmapped virtual memory. Because the memory I'm allocating isn't mapped, I can't use a normal memory allocator, as most of them...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.