Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How allocate memory which is page size aligned?

I need to allocate memory which should be page size aligned. I need to pass this memory to an ASM code which calculates xor of all data blocks. I need to do this with malloc().

like image 283
Chinna Avatar asked Feb 04 '14 10:02

Chinna


4 Answers

There are functions for this that you're supposed to use.

If you can't, for whatever reason, then the way this is generally done is by adding the block size to the allocation size, then using integer-math trickery to round the pointer.

Something like this:

/* Note that alignment must be a power of two. */
void * allocate_aligned(size_t size, size_t alignment)
{
  const size_t mask = alignment - 1;
  const uintptr_t mem = (uintptr_t) malloc(size + alignment);
  return (void *) ((mem + mask) & ~mask);
}

This has not been very deeply tested but you get the idea.

Note that it becomes impossible to figure out the proper pointer to free() the memory later. To fix that, we would have to add some additional machinery:

typedef struct {
  void *aligned;
} AlignedMemory;

AlignedMemory * allocate_aligned2(size_t size, size_t alignment)
{
  const size_t mask = alignment - 1;
  AlignedMemory *am = malloc(sizeof *am + size + alignment);
  am->aligned = (void *) ((((uintptr_t) (am + 1)) + mask) & ~mask);
  return am;
}

This wraps the pointer trickery a bit, and gives you a pointer you can free(), but you need to dereference into the aligned pointer to get the properly aligned pointer.

like image 118
unwind Avatar answered Oct 18 '22 10:10

unwind


I don't think is possible only with malloc. You can use memalign():

char *data = memalign(PAGESIZE, alloc_size);

Where PAGESIZE is the size of a page and alloc_size is the size of the memory that will be allocated.

The size of the page can be found with sysconf(_SC_PAGESIZE).

like image 42
fede1024 Avatar answered Oct 18 '22 10:10

fede1024


Use posix_memalign to obtain memory already aligned.

Note: valloc & memalign both are obsoleted.

like image 9
Sunil Bojanapally Avatar answered Oct 18 '22 11:10

Sunil Bojanapally


Use valloc rather than malloc - it has the same signature as malloc but it allocates page-aligned memory. Note that you still free the memory subsequently using free().

Note also that valloc is technically obsolete, so consider using posix_memalign, although this is not such a simple replacement for malloc as it has a very different function signature.

like image 2
Paul R Avatar answered Oct 18 '22 11:10

Paul R