Need to align memory on a power of 2 and align the program break on a multiple of 2 * getpagesize() in C

1k Views Asked by At

I'm re-coding the malloc function using brk, sbrk & getpagesize()

I must follow two rules:

1) I must align my memory on a power of 2

It means: If the call to malloc is : malloc(9); i must return them a block of 16 byte. ( the nearest power of 2);

2) I must align the break (program end data segment) on a multiple of 2 pages.

I'm thinking about the rules, i'm wondering if i'm true;

Rule 1) I just need to make the return of my malloc (so the adress returned by malloc in hexa) a multiple of 2 ?

And for the Rule 2)

the break is the last adress in the heap if i'm not wrong, do i need to set my break like this (the break - the heap start) % (2 * getpagesize())== 0? or just the break % (2 * getpagesize() == 0? Thanks

1

There are 1 best solutions below

3
Eric Postpischil On

1) I must align my memory on a power of 2

Rule 1) I just need to make the return of my malloc (so the adress returned by malloc in hexa) a multiple of 2 ?

For an address to be aligned on power of 2 that is 2p, the address must be a multiple of 2p.

2) I must align the break (program end data segment) on a multiple of 2 pages.

the break is the last adress in the heap if i'm not wrong, do i need to set my break like this (the break - the heap start) % (2 * getpagesize())== 0? or just the break % (2 * getpagesize() == 0?

The phrase “set my break” is unclear. You need to use sbrk(0) to get the current value of the break and calculate how much you need to add to it to make it a multiple of twice the page size. That tells you where you need to start a block of memory that is aligned to a multiple of twice the page size. Then you need additional memory to contain whatever amount of data you want to put there (the amount being allocated).