473,770 Members | 2,160 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to allocate memory which is 2^k aligned

Hi,
can somebody help me figure out how can I make write a function
which inturn uses malloc routine to allocate memory which is 2^k
aligned?

The condition is such that there should not be any memory leak and it
should not also waste memory.

Thanks,
Divick

Sep 5 '06 #1
11 3189
Divick wrote:
can somebody help me figure out how can I make write a function
which inturn uses malloc routine to allocate memory which is 2^k
aligned?

The condition is such that there should not be any memory leak and it
should not also waste memory.
I think you're looking to calculate the next power of 2 from a number.
Given that you need to allocate N bytes, the N is not necessarily any
power of 2, so you need to find the next power of 2 that is not smaller
than N. You can do it in a loop.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Sep 5 '06 #2
Divick posted:
Can somebody help me figure out how can I make write a function
which inturn uses malloc routine to allocate memory which is 2^k
aligned?

"malloc" does this already -- it allocates memory whose alignment is strict
enough to satisfy the alignment of any kind of object.

You might like "aligned_storag e" aswell (Google for it), although it
allocates on the stack rather than on the heap.

--

Frederick Gotham
Sep 5 '06 #3
Divick wrote:
>
can somebody help me figure out how can I make write a function
which inturn uses malloc routine to allocate memory which is 2^k
aligned?

The condition is such that there should not be any memory leak and it
should not also waste memory.
For more or less arbitrary values of k, the only way to do it is to
allocate a block that's sure to be large enough (i.e. 2^(k+1)) and pick
off an address within that block that meets your alignment requirements.

For values of k such that 2^k is the alignment of some type (typically
2, 4, 8, or 16 bytes), malloc returns a pointer that's suitably aligned
for any type, so you don't need to do anything special.

--
-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Sep 5 '06 #4
Frederick Gotham wrote:
Divick posted:
Can somebody help me figure out how can I make write a function
which inturn uses malloc routine to allocate memory which is 2^k
aligned?

"malloc" does this already -- it allocates memory whose alignment is strict
enough to satisfy the alignment of any kind of object.
But malloc only satisfies the alignment requirements of the
implementation - e.g. hardware alignment requirements. The application
may have stricter requirements depending on what you want to do.

Regards,
Bart.

Sep 5 '06 #5
For more or less arbitrary values of k, the only way to do it is to
allocate a block that's sure to be large enough (i.e. 2^(k+1)) and pick
off an address within that block that meets your alignment requirements.

For values of k such that 2^k is the alignment of some type (typically
2, 4, 8, or 16 bytes), malloc returns a pointer that's suitably aligned
for any type, so you don't need to do anything special.
Since I have constraint that I have to use malloc in my application and
I also want that once that memory is passed to me I should be able to
free the memory. Thus simply returning the offset will not solve my
purpose as once the application passes the same location to me , I will
pass the location to free and free wouldn't know that it was actually
allocated. See the code below

The problem with the code below is that free does not know how to free
the memory because I pass it the address which malloc didn't return.
The other problem is that lot of memory gets wasted. Is there a way to
overcome such problems?

#define ALIGNMENT_K 3

void * allocate_memory (size_t size)
{
//allocate memory so that at least there is an address which is
2^k aligned
char * mem = (char *)malloc(size + 2^ALIGNMENT_K);

//calculate offset and if it is not 2^k aligned then
//increment the pointer till it is.
while( (*mem & ~(0xffffffff << ALIGNMENT_K)) != 0 )
{
mem++;
}

return (void *)mem;
}

//If the mem pointer is not the same that malloc returned then it
//is a problem and free won't be able to free the memory
void free_memory(voi d * mem)
{
free(mem);
}

I hope I am clear in my question and intent.

Thanks,
Divick

Sep 6 '06 #6
But malloc only satisfies the alignment requirements of the
implementation - e.g. hardware alignment requirements. The application
may have stricter requirements depending on what you want to do.
Yup exactly that is what my problem is. Thanks for asserting in a clear
way.

Divick

Sep 6 '06 #7

Divick wrote:
Hi,
can somebody help me figure out how can I make write a function
which inturn uses malloc routine to allocate memory which is 2^k
aligned?

The condition is such that there should not be any memory leak and it
should not also waste memory.
There is no portable way. But why do you want a specific alignment in
the first place? The reason for this must be for some nonportable
reason and the platform your program is to run on likely will support
such a call - or at least just waste virtual (not real) memory.

/Peter

Sep 6 '06 #8
Divick <di************ @gmail.comwrote :
>Since I have constraint that I have to use malloc in my application and
I also want that once that memory is passed to me I should be able to
free the memory. Thus simply returning the offset will not solve my
purpose as once the application passes the same location to me , I will
pass the location to free and free wouldn't know that it was actually
allocated. See the code below

The problem with the code below is that free does not know how to free
the memory because I pass it the address which malloc didn't return.
The other problem is that lot of memory gets wasted. Is there a way to
overcome such problems?
It seems you have to write your own version of free() that contains
a map between the original values returned by malloc() and
the aligned values passed to the application.

This should be reasonably easy using a std::map.

Steve
Sep 6 '06 #9

Divick wrote:
Hi,
can somebody help me figure out how can I make write a function
which inturn uses malloc routine to allocate memory which is 2^k
aligned?

The condition is such that there should not be any memory leak and it
should not also waste memory.
you could try something like

template <std::size_t Size, std::size_t Align>
struct aligned_str
{
boost::aligned_ storage<Size, Alignaligned_;
};

typedef aligned_str<Siz e, Alignmy_aligned ;
my_aligned * p = static_cast<my_ aligned*>(mallo c(sizeof(my_ali gned));
// and use
p->aligned_.addre ss();

Sep 7 '06 #10

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

Similar topics

37
4680
by: Curt | last post by:
If this is the complete program (ie, the address of the const is never taken, only its value used) is it likely the compiler will allocate ram for constantA or constantB? Or simply substitute the values in (as would be required if I used the hideous, evil, much-abused #define :) ----------- const int constantA = 10; static const int constantB = 20;
4
1763
by: alan | last post by:
Dear all, I am a newbie in C++. If I want to allocate memory to objects, I will use double *d = new double instead of ANSI-C malloc. But if I want to resize, say enlarge num of objects to 20, how can I do it? In ANSI-C, I can use realloc to do this.
4
2591
by: Franklin Lee | last post by:
Hi All, I use new to allocate some memory,even I doesn't use delete to release them. When my Application exit, OS will release them. Am I right? If I'm right, how about Thread especally on Solaries OS? This means that I use new to allocate memory in one Thread and doesn't use delete to release them.
4
5002
by: marora | last post by:
I have created class definition which contains a charater pointer as one of it's data memeber. The objective is to read some data from a file, and assign it to a data member; Size of data is not known in the begining. We can assume that it will not exceed 256; class definition:
13
9727
by: shsingh | last post by:
I have a class A containing some map as data variables. I creat an object of class A on heap by allocatiing memory by using "malloc". This will return me the required memory but the object is not initialized properly as constructor same is not get called ( as per the behavior). How to call a constructor explicitly if we want to allocate memory using malloc ?
14
2641
by: raghu | last post by:
Hello , This is Raghu. I have a problem in declaring a structure. Consider struct hai{ int id; char sex; int age; }; here when a variable is instianted for this structure then immediately
5
1789
by: raghu | last post by:
Hello , This is Raghu. I have a problem in declaring a structure. Consider struct hai{ int id; char sex; int age; }; here when a variable is instianted for this structure then immediately
0
1951
by: Varav | last post by:
We have a simple web service for DB2 to consume. I have tested the SOAPHTTPV and it is pretty slick. It is great that a database can do this. I first tested single requests over and over by hand and that works fine. However, we could easily have multiple requests being made right after each other or at the same time. To test this scenerio, I called the SOAPHTTPV method by doing: select db2xml.soaphttpv...
1
2184
by: darkdai | last post by:
hey everyone im trying to write a code that will have different functions which will allocate memory, de-allocate, reallocate etc. this is my code #include<stdio.h> #include<stdlib.h> void main() { void allocate(int *ptr); void reallocate(int *ptr); void ffr(int *ptr); int ans=0; int *ptr;
0
9454
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,...
0
10101
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10038
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
9906
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
8933
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
7456
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
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
3
2850
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.