Giang
Giang

Reputation: 51

How to allocate a region of memories which similar VirtualAlloc?

I was looking for a method of allocating memories on Linux which similar VirtualAlloc on Windows. Requirements are:

  1. Size of memories block to allocate is 2^16.
  2. Address of memories block is larger than 0x0000ffff
  3. Address of memories block must have last 16 bits are zero.

On Windows because lower limit of application address (lpMinimumApplicationAddress) we have (2) obvious right. From (1), (2) and system rules we also achieved (3).

Thanks for helping.

Upvotes: 1

Views: 1393

Answers (3)

caf
caf

Reputation: 239041

You want posix_memalign():

void *ptr;
int memalign_err = posix_memalign(&ptr, 1UL << 16, 1UL << 16);

if (memalign_err) {
    fprintf(stderr, "posix_memalign: %s\n", strerror(memalign_err));
} else {
    /* ptr is valid */
}

The first 1UL << 16 is the alignment, and the second is the size.

When you're done with the block you pass it to free().

Upvotes: 0

sherpya
sherpya

Reputation: 4936

you can ask a specific address to mmap, it may fail for some specific addresses, but generally it works

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283664

Try mmap(..., MAP_ANONYMOUS, ...)

You'll get an address which is aligned to a page boundary. For more stringent alignment than that, you probably need to allocate extra and pick an address inside your larger block than is correctly aligned.

Upvotes: 1

Related Questions