473,546 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Custom memory allocator - alignment

I have a need to make a custom quasi-memory allocator, and I remembered
a simple ons in K&R2. Looking at the code for it now, I think I notice
a "fault" in the design, and I was wondering if people would back me up
on this.

The design basically uses a pool of memory, allocated as a character
array. Pointers into the array are retured by the allocated function.
Isn't this very dangerous, as a char has very lenient memory alignment
requirements, which would allow the compiler to allocate the array
starting at a location that might not be a multiple of an address
required for other type. Also, pointers in the middle of the arrat
(after the first allocation) will certainly be unaligned for some
types.

My fix, is to use an array of ints (as they match the natural size for
my syste), and then use a pointer into this array of ints. When
returning the pointer value, I could cast it to (void *).

Isn't this much safer than the char array versoin?

Can someone correct me on this, or verify my line of thoughts? thx

Nov 14 '05 #1
4 4116
In article <11************ *********@z14g2 000cwz.googlegr oups.com>
Romeo Colacitti <ww*****@gmail. com> wrote:
I have a need to make a custom quasi-memory allocator, and I remembered
a simple ons in K&R2. Looking at the code for it now, I think I notice
a "fault" in the design, and I was wondering if people would back me up
on this.

The design basically uses a pool of memory, allocated as a character
array. Pointers into the array are retured by the allocated function.
Isn't this very dangerous, as a char has very lenient memory alignment
requirements ...
It is indeed unsuitable as a general-purpose allocator. (As a
char-array allocator it works fine, of course.)
My fix, is to use an array of ints (as they match the natural size for
my syste), and then use a pointer into this array of ints. When
returning the pointer value, I could cast it to (void *).

Isn't this much safer than the char array versoin?


Well, how much is "much"? Safe*r*, yes, but perhaps not so much.
In particular it will not fix the problem on machines with 4-byte
"int"s and 8-byte alignment requirements, such as SPARC and MIPS
processors.

ANSI/ISO C, for whatever reasons, does not give one the tools
required to write malloc() in pure ANSI/ISO C. I find this somewhat
unfortunate, but for those who want to press on regardless, it
usually suffices to have the two macros we put into <machine/param.h>
on 4.xBSD systems: ALIGN(p) takes an arbitrary pointer-or-"intptr_t"
value p, and returns an aligned variant of it (as an intptr_t),
which has possibly been increased by some number of bytes ("char"s);
and ALIGNBYTES is the maximum such increase.

In other words, on a BSD system, you can write a malloc() clone
using ALIGNBYTES (to know how many extra bytes to allocate for
rounding) and ALIGN() (to align pointers). You can also use these
for other sneaky allocation tricks involving malloc() itself.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #2
Chris Torek wrote:
In article <11************ *********@z14g2 000cwz.googlegr oups.com>
Romeo Colacitti <ww*****@gmail. com> wrote:

The design basically uses a pool of memory, allocated as a character
array. Pointers into the array are retured by the allocated function.Isn't this very dangerous, as a char has very lenient memory alignmentrequirements ...
It is indeed unsuitable as a general-purpose allocator. (As a
char-array allocator it works fine, of course.)


Thank you for clearing that up. The lack of a warning in K&R got me
confused.
My fix, is to use an array of ints (as they match the natural size formy syste), and then use a pointer into this array of ints. When
returning the pointer value, I could cast it to (void *).

Isn't this much safer than the char array versoin?
Well, how much is "much"? Safe*r*, yes, but perhaps not so much.
In particular it will not fix the problem on machines with 4-byte
"int"s and 8-byte alignment requirements, such as SPARC and MIPS
processors.


Oh. I would have thought that most implementations (like mine) would
make sizeof "int" equal to the alignment requirement.

ANSI/ISO C, for whatever reasons, does not give one the tools
required to write malloc() in pure ANSI/ISO C.
Is malloc usually coded in assembly?
I find this somewhat
unfortunate, but for those who want to press on regardless, it
usually suffices to have the two macros we put into <machine/param.h>
on 4.xBSD systems: ALIGN(p) takes an arbitrary pointer-or-"intptr_t"
value p, and returns an aligned variant of it (as an intptr_t),
which has possibly been increased by some number of bytes ("char"s);
and ALIGNBYTES is the maximum such increase.

When it returns the aligned variant, does it copy over the contents of
the object too?

In other words, on a BSD system, you can write a malloc() clone
using ALIGNBYTES (to know how many extra bytes to allocate for
rounding) and ALIGN() (to align pointers). You can also use these
for other sneaky allocation tricks involving malloc() itself.


Well beyond my comprehension, but thank you for clearing up my massive
confusion. I will use an array of ints in my case.

Nov 14 '05 #3
On 3 Mar 2005 22:26:25 -0800, "Romeo Colacitti" <ww*****@gmail. com>
wrote:
Chris Torek wrote:
In article <11************ *********@z14g2 000cwz.googlegr oups.com>
Romeo Colacitti <ww*****@gmail. com> wrote:
>
>The design basically uses a pool of memory, allocated as a character
>array. Pointers into the array are retured by the allocatedfunction. >Isn't this very dangerous, as a char has very lenient memoryalignment >requirements ...


It is indeed unsuitable as a general-purpose allocator. (As a
char-array allocator it works fine, of course.)


Thank you for clearing that up. The lack of a warning in K&R got me
confused.


have you read K&R2 malloc implementation?
no and NO, K&R2 malloc returns arrays of units aligned to 8 bytes in
my x86>=386 Pc and borland C compiler this seems good; sizeof(long)=4;
but this not fits the other restriction sizeof(long double)=10. it
seems I remember that if an array of long double 10bytes are aligned
to 8bytes => x86 cpu can perform operations but 2x more slow: is it
true?

How about change *here in my pc&cpu* "Align long" with
"Align long double"?
(so there is not problems with long double arrays)
Thank you very much
Nov 14 '05 #4
[snippage throughout]
Chris Torek wrote:
Well, how much is "much"? Safe*r*, yes, but perhaps not so much.
In particular it will not fix the problem on machines with 4-byte
"int"s and 8-byte alignment requirements, such as SPARC and MIPS
processors.
In article <11************ *********@o13g2 000cwo.googlegr oups.com>
Romeo Colacitti <ww*****@gmail. com> wrote:
Oh. I would have thought that most implementations (like mine) would
make sizeof "int" equal to the alignment requirement.
Well, when "maximum alignment" is 128 bytes, do you really want
128-byte "int"s? Even if maximum alignment is a mere 8 or 16 bytes,
as is the case on many modern CPUs, are you sure you want to commit
to having at-least-8-byte "int"s (so that INT_MAX is 922337203685477 5807)
on modern 64-bit CPUs? If so, what will you use for a four-byte
type, if "char" is to be one 8-bit byte and "short" is to be two?
ANSI/ISO C, for whatever reasons, does not give one the tools
required to write malloc() in pure ANSI/ISO C. Is malloc usually coded in assembly?
I would imagine not. But one need not resort to assembly code,
when non-portable C will suffice. The problem then lies in the
fact that the code is non-portable, so that moving it from machine
A to machine B causes it to break.
... for those who want to press on regardless, it
usually suffices to have the two macros we put into <machine/param.h>
on 4.xBSD systems: ALIGN(p) takes an arbitrary pointer-or-"intptr_t"
value p, and returns an aligned variant of it (as an intptr_t),
which has possibly been increased by some number of bytes ("char"s);
and ALIGNBYTES is the maximum such increase.

When it returns the aligned variant, does it copy over the contents of
the object too?


I fear you misunderstand: the ALIGN macro does no copying whatsoever.
In fact, three actual implementations , for three different machines,
are:

/* Intel, before SSE */
#define ALIGNBYTES 3
#define ALIGN(p) (((intptr_t)(p) + 3) & ~3)

and:

/* SPARC and MIPS */
#define ALIGNBYTES 7
#define ALIGN(p) (((intptr_t)(p) + 7) & ~7)

and:

/* Intel, when using SSE */
#define ALIGNBYTES 15
#define ALIGN(p) (((intptr_t)(p) + 15) & ~15)

It makes little sense to apply ALIGN() to a pointer after storing
value(s) into the memory to which it points, because the whole
point of applying the ALIGN() macro is to come up with a "well-aligned"
pointer, so that *(type)ptr = value works regardless of the given
pointer-type (char *, int *, double *, long double *, float (**)[5],
short *(**)(int), whatever).

Note that the definition on a Data General Eclipse might perhaps
be:

#define ALIGNBYTES 3
#define ALIGN(p) (((intptr_t)(p) + 1) & ~1)

(depending on the rules for conversion of arbitrary pointers to
type "intptr_t" -- this assumes the conversion produces a word
pointer in all cases), so it is not necessarily the case that
the "number of bytes" (chars) needed is the same as the constant
added-and-masked-out. (If the conversion from pointer-to-integer
and back does not account for byte pointers vs word pointers,
these macros will not suffice, at least not without additional
rules not present in the BSD implementations .)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #5

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

Similar topics

18
6657
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 hard drive file system. Over time, the more often use call new/delete or alloc/free, there will be gaps and fragments in the heap. This can lead...
12
2405
by: Brian Genisio | last post by:
Hi all, I am developing some software, that creates a tree of information. For each node, currently I am overriding the new operator, because it is a requirement that after initialization, no new memory may be allocated. It also needs to be thread safe, and each thread has a context, so any allocation of nodes currently looks like this:...
7
2350
by: serikas | last post by:
Is there a way to get aligned dynamically allocated memory? (provided that the requested memory size is a power of 2.) For example, if I request 128 bytes of memory, can I implement an allocator that allocates 128 bytes with 128-byte alignment? Of course I know that it is possible by allocating twice the requested size or more, but I...
13
5713
by: Michael B Allen | last post by:
Hi, I've tried to write the *simplest* memory allocator possible. I think it would be useful in many cases such as allocating memory on stack as a poor man's garbage collection perhaps. I was hoping the clc crowd had some ideas for making it even simpler! In-lined below the full program (132 lines). It's a circular singular linked list...
5
1897
by: mikegw | last post by:
Hello all. I am currently using an implementation of sysV shared memory. The entire shared memory is allocated is one continuous block of which I get the pointer to the head, everything should be done as offsets from this. At the moment I have two data structures, a head to a linked list which in it contains the pointer to the first...
3
2139
by: Alex Vinokur | last post by:
Compiler GNU g++ version 3.4.4 (cygming special) Custom allocator for vector (see below) checks a return value of 'operator new'. If that value is NULL, the allocator "allocates" no memory. Nevertheless the allocator produces "Segmentation fault (core dumped)". Is it possible to correct that allocator in order to avoid such behavior ...
3
1894
by: joe | last post by:
I have written a custom std allocator which follows the example in Stroustrup's book. I'm seeing a behavior I don't understand. My allocate method within the allocator looks like the following: (FooAllocator<T>) pointer allocate(size_type cnt, typename std::allocator<void>::const_pointer hint = 0)
1
2069
by: Chris Thomasson | last post by:
I found some time to work a little more on my C++ allocator project. Here is some of the basic alignment code that I am thinking about using: ---------------- #include <cstdio> #include <cstring> #include <cassert> // attempts to extract the alignemnt of a type T
31
1650
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> typedef union aligner_types_u aligner_types; typedef struct aligner_offset_s aligner_offset;
0
7435
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7947
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6030
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5361
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3492
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3472
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1922
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1046
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
747
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.