473,781 Members | 2,729 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Heap management

So seems to be slightly wrong group, but...

The question is: Is there any extentions for C or well known libraries
to implement heap managment, for example if I want to allocate a randome
data in the static array of chars? For example:

Heap *heap_new (void *ptr, size_t size/*, may be some other
arguments*/);
void heap_delete (Heap *heapp);
void *heap_alloc (Heap *heapp, size_t object_size);
void *heap_realloc (Heap *heapp, void *alloced_object , size_t new_size);
void heap_free (Heap *heapp, void *alloced_object );

K&R book has a sample implementation of this, but is there a more
effective implementations and what do you think about including such
mecanism to a standard library (as a backend for malloc and co.)?

--
vir
Nov 14 '05 #1
6 2290
In article <ce***********@ news.comcor-tv.ru>
Victor Nazarov <vi*@comtv.ru > writes:
So seems to be slightly wrong group, but...

The question is: Is there any extentions for C or well known libraries
to implement heap managment, for example if I want to allocate a randome
data in the static array of chars? For example:

Heap *heap_new (void *ptr, size_t size/*, may be some other
arguments*/);
void heap_delete (Heap *heapp);
void *heap_alloc (Heap *heapp, size_t object_size);
void *heap_realloc (Heap *heapp, void *alloced_object , size_t new_size);
void heap_free (Heap *heapp, void *alloced_object );
Your examples suggest to me that you want to write a set of functions
that work a lot like malloc/realloc/free, but on specific arenas
-- so that, for instance, you can create one area of size "3000
bytes" and make sure that whatever is allocated in that area, the
entire area never consumes more than 3000 bytes.

It *is* possible to write malloc()-like functions in C, and there are
existing libraries of such functions (to find them, try google or
perhaps comp.sources.wa nted), except for one problem: ANSI/ISO C
lacks the ability to tell you what "maximal alignment" *is*. The
malloc() family always returns a "maximally aligned" pointer, so
that you can do things like:

char *p;
float *q;
long complex double *r;

p = malloc(NP * sizeof *p);
q = malloc(NQ * sizeof *q);
r = malloc(NR * sizeof *r);

and if p, q, or r are not NULL afterward, they are all valid pointers
pointing to the first of NP, NQ, or NR objects, so that (for
instance) r[i] is valid for all integer values of i in [0..NR).

If you try to write your own malloc()-like function, however,
there is no *portable* way to find out what alignment to use.
In the example above, you can make a union:

union align { char c; float f; long complex double lcd; };

and use "sizeof(uni on align)" as a clue to the alignment required
to handle all of p, q, and r; but what if for some reason "short"
requires more alignment than "long complex double"? You can add
"short" to the union, but then what if the maximal alignment type
is actually "int *(*)(long)" or some such? No matter what types
you add to "union align", you *could* miss the underlying system's
"strictest" type, whatever that is.

If ANSI/ISO C had merely provided some sort of "alignment testing
and adjusting" macros or functions, then -- and only then -- would
there be some portable method for you to get the implementation
to tell you how to align pointers you would return from your own
malloc()-like functions, so that they would always work for every
valid piece of C code. But alas, none of the C standards (past or
present) do this.

Ultimately, what this really means is that while you *can* write
your own malloc()-like functions, you must resort to some non-Standard
trick to discover the alignment value. If you put this trick in
file(s) that you simply port or write anew every time you change
compilation environments, you can solve the problem relatively
cleanly.
... and what do you think about including such
mecanism to a standard library (as a backend for malloc and co.)?


If you study the CS literature, you will find dozens of memory
allocation strategies. There is no single best method for all
problems. (This is another reason I find the lack of a Standard
method for discovering alignment restrictions somewhat annoying.
On the other hand, when writing specialized, tuned allocators for
particular problems, you may already know all the data-types
involved, in which case the "union align" method generally suffices.)
--
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:

I've knew most of your answers before. Thank you anyway. I have proposed
to involve heap_alloc and similar function to generalize standart
allocator. The idia was to make such functions that malloc could be
defined and implemented using these more general functions, not
nessesaraly the most effective for particular purpose.
If you study the CS literature, you will find dozens of memory
allocation strategies. There is no single best method for all
problems. (This is another reason I find the lack of a Standard
method for discovering alignment restrictions somewhat annoying.
On the other hand, when writing specialized, tuned allocators for
particular problems, you may already know all the data-types
involved, in which case the "union align" method generally suffices.)

I understand that if I'll nedd an effective allocator I'll need to write
an allocator suited for the particular application myself.

And I have two questions:
!) If I wrote an allocator using the union of all allocatable objects fo
alignment, would it be the most effictive in space usage, could it be
optimized to use less space with the help of system specific alignment
information?

2) What do think might be included in the standard lib to provide
alignment information?

--
vir
Nov 14 '05 #3
In article <ce***********@ news.comcor-tv.ru>
Victor Nazarov <vv*****@mail.r u> writes:
... And I have two [more] questions:
!) If I wrote an allocator using the union of all allocatable objects fo
alignment, would it be the most effictive in space usage, could it be
optimized to use less space with the help of system specific alignment
information?
Quite possibly. Note, one way to get what the *compiler* considers the
"minimal" alignment is to do something like this:

struct align {
char offset_zero;
/* padding goes here */
union {
/* this list will probably work in most cases */
int i;
long l;
long long ll; /* C99 only */
double d;
long double ld;
long double complex lcx; /* C99 only */
char *cp;
int *ip;
void (*fp)(void);
} u;
};
/* now use offsetof(struct align, u) to get alignment in bytes */
2) What do think might be included in the standard lib to provide
alignment information?


For 4.4BSD, I convinced the appropriate people to add two macros
to <machine/param.h>: ALIGNBYTES, whish is an integral constant
that is the largest number of "extra bytes" required to align
some pointer "p", and ALIGN(p), which is an expression that produces
an aligned value that is no less than "p" but perhaps as many as
ALIGNBYTES bytes "beyond" the initial value in p.

The type of the ALIGN(p) macro was "unsigned int", but in C99,
would be better expressed as intptr_t, or perhaps just "char *".

One problem with the ALIGN() macro is that it takes an arbitrary
pointer (of any type); 4.xBSD "gets away" with this by assuming
that these Unix-like systems are never going to run correctly on
any machine that is not inherently byte-addressed.

I think, however, that if one were to constrain the ALIGN macro
(or function, should it be made into a function in a future C
standard) to take a value of type "char *", these two -- ALIGNBYTES
and ALIGN -- would suffice. Note that:

ALIGN(p) - p /* p must have type "char *" */

would then have type "ptrdiff_t" and be a value between 0 and
ALIGNBYTES inclusive, e.g., 0 to 3, or 0 to 7, or 0 to 31, or
whatever the underlying system requires.

The actual implementation of ALIGN(p), on many real systems, is
then just:

#define ALIGN(p) \
((char *)(((intptr_t)( p) + ALIGNBYTES) & ~ALIGNBYTES))

On systems where this does *not* work, for whatever reason (such
as Cray systems with word addressing and "byte offsets" stashed
in high-order bits), some alternative macro invariably seems to
work.
--
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 #4

"Victor Nazarov" <vv*****@mail.r u> wrote in message

I've knew most of your answers before. Thank you anyway. I have proposed
to involve heap_alloc and similar function to generalize standart
allocator. The idia was to make such functions that malloc could be
defined and implemented using these more general functions, not
nessesaraly the most effective for particular purpose.
You can write mymalloc() and myfree() and then implement them as you want.
The problem is that you make all your code dependent on this library.
Or you can call the functions malloc() and free(), effectively implementing
the standard library, but then the linker tends to complain on hosted
platforms.
And I have two questions:
!) If I wrote an allocator using the union of all allocatable objects fo
alignment, would it be the most effictive in space usage, could it be
optimized to use less space with the help of system specific alignment
information?
If you are bothered about a few bytes wasted at the beginning of an
allocation for alignment, then rethink the memory management of the whole
program. Probably you are allocating many very small chunks, so write a
"fixedalloc ()" to allocate them efficiently.
But no, there is no easy way to determine alignment requirements in ANSI C.
2) What do think might be included in the standard lib to provide
alignment information?

The practical answer is to align to "double", and this will be portable
enough for most systems. It is a weakness in the standard that malloc cannot
be written portably, and I would solve it by creating a special type,
"strictest" . On most compilers this would simply be implemented as a header
typedefing "strictest" , though on an oddball it could be a keyword.
Nov 14 '05 #5
Chris Torek <no****@torek.n et> writes:
In article <ce***********@ news.comcor-tv.ru>
Victor Nazarov <vv*****@mail.r u> writes:
... And I have two [more] questions:
!) If I wrote an allocator using the union of all allocatable objects fo
alignment, would it be the most effictive in space usage, could it be
optimized to use less space with the help of system specific alignment
information?


Quite possibly. Note, one way to get what the *compiler* considers the
"minimal" alignment is to do something like this:

struct align {
char offset_zero;
/* padding goes here */
union {
/* this list will probably work in most cases */
int i;
long l;
long long ll; /* C99 only */
double d;
long double ld;
long double complex lcx; /* C99 only */
char *cp;
int *ip;
void (*fp)(void);
} u;
};
/* now use offsetof(struct align, u) to get alignment in bytes */


And you can probably get away with dropping the int and double members
(and the long, and perhaps long double, members for C99). It's
unlikely that double will have stricter alignment requirements than
long double. A system that's exotic enough to break this assumption
may have other problems as well, like requiring stricter alignment for
large structures.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #6

"Keith Thompson" <ks***@mib.or g> wrote in message

And you can probably get away with dropping the int and double members
(and the long, and perhaps long double, members for C99). It's
unlikely that double will have stricter alignment requirements than
long double. A system that's exotic enough to break this assumption
may have other problems as well, like requiring stricter alignment for
large structures.

If I had a processor with 32 and 64 bit fpus, I'd make the smaller float and
the larger double. long double would then be supported in software to cater
for the person who needs precison but doesn't care about speed. It would be
quite likely that double would have a stricter alignment than long double.
Nov 14 '05 #7

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

Similar topics

17
5052
by: Jonas Rundberg | last post by:
Hi I just started with c++ and I'm a little bit confused where stuff go... Assume we have a class: class test { private: int arr; };
7
1749
by: Michael Cornelison | last post by:
I believe I have found a serious performance problem with heap management in C++ .Net. I have an application does the following thousands of times: vint = new int; vchar = new char; The performance of these vector creations varies by a factor of 40 or more. It is also sensitive to the
3
1972
by: Aravindakumar Venugopalan | last post by:
Hi , A Windows form application which interacting with the unmanaged C++ codes . In unmanaged c++ code we allocate around 130MB on the heap for annalysing high resolution images . Earlier during the processing ee do lot of process on the image and the memory reaches high at one point of time to 1.2GB , after that we clear all the memory being used so the memory in the task manager comes to really low. Also I am calling CompactHeap...
24
2896
by: arcticool | last post by:
I had an interview today and I got destroyed :( The question was why have a stack and a heap? I could answer all the practical stuff like value types live on the stack, enums are on the stack, as are structs, where classes are on the heap... when value types go out of scope the memory is re- allocated, object remain in memory waiting to be cleaned up by the garbage collector, etc, but he responded 'so why not just put say a class on the...
16
4451
by: sarathy | last post by:
Hi all, I need a few clarifications regarding memory allocaion in C++. I apologize for the lengthy explanation. 1. In C++, Objects are allocated in heap. What does heap refer to? Is it an area in RAM/Memory or does it refer to a data structure being used for storing objects. 2. In C++, functions and its local variables go in stack. If local variables that are primitives go in stack, it is OK. But what
1
3615
by: Chris Mullins | last post by:
We've been using the SSLStream class found in System.Net.Security to build a giant Sockets server that provides TLS encryption at the channel leve. Before .Net 2.0, we used an open-source encryption channel from Mentalis, and have even looked at the Mono implementation for doing this. The problem comes from the SSLStream not doing any buffer management. None. Zero. In the "no buffer management" case, each SSLStream allocates bufferes...
53
26403
by: fdmfdmfdm | last post by:
This is an interview question and I gave out my answer here, could you please check for me? Q. What are the memory allocation for static variable in a function, an automatic variable and global variable? My answer: static variable in function and global variable are allocated in head, and automatic variable is allocated in stack. Right?
11
5216
by: Andy Watson | last post by:
I have an application that scans and processes a bunch of text files. The content I'm pulling out and holding in memory is at least 200MB. I'd love to be able to tell the CPython virtual machine that I need a heap of, say 300MB up front rather than have it grow as needed. I've had a scan through the archives of comp.lang.python and the python docs but cannot find a way to do this. Is this possible to configure the PVM this way? ...
9
3174
by: Roman Mashak | last post by:
Hello, I'm confused about heap and stack memories management in C language. Most books explain that local stack variables for each function are automatically allocated when function starts and deallocated when it exits. In contrast, malloc() always takes memory in the heap. Now, let's consider the code as follows: int get_buffer() {
5
24804
by: kumarmdb2 | last post by:
Hi guys, For last few days we are getting out of private memory error. We have a development environment. We tried to figure out the problem but we believe that it might be related to the OS (I am new to Windows so not sure). We are currently bouncing the instance to overcome this error. This generally happen at the end of business day only (So maybe memory might be getting used up?). We have already increased the statement heap & ...
0
9639
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9474
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10076
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9939
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8964
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7486
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6729
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3633
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2870
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.