tags:

views:

136

answers:

4

Windows has VirtualAlloc, which allows you to reserve a contiguous region of address space, but not actually use any physical memory. Later when you want to use it (or part of it) you call VirtualAlloc again to commit the region of previously reserved pages.

This is actually really useful, but I want to eventually port my application to linux - so I don't want to use it if I can't port it later. Does linux have a way to do this?

EDIT - Use Case

I'm thinking of allocating 4 GB or some such of virtual address space, but only committing it 64K at a time. This would give me a zero-copy way to grow an array up to 4 GB. Which is important, because the typical double the array size and copy introduces seemingly random unacceptable latency for very large arrays.

+3  A: 

You can turn this functionality on system-wide by using kernel overcommit. This is usually default setting on many distributions.

Here is the explanation http://www.mjmwired.net/kernel/Documentation/vm/overcommit-accounting

Vlad
Oh that is cool... Can't turn it on for only a single process though huh?
xyld
+4  A: 

mmap a special file, like /dev/zero (or use MAP_ANONYMOUS) as PROT_NONE, later use mprotect to commit.

Ben Voigt
Yes. The C library / kernel effectively implicitly does this anyway when you allocate a chunk of memory of any size normally. Pages are reserved but not actually mapped until you touch them. Mapping /dev/zero (with MAP_PRIVATE) is just a special kind of malloc.
MarkR
@MarkR: That's true for linux, for certain settings of the vm overcommit sysctl. The mmap of `/dev/zero` approach ought to work on any POSIX OS including linux with vm overcommit disabled. Reading the vm overcommit documentation, the combination of `/dev/zero` and no write access is what causes the block to not count against the commit limit.
Ben Voigt
+1  A: 

The Linux equivalent of VirtualAlloc() is mmap(), which provides the same behaviours. However as a commenter points out, reservation of contiguous memory is the behaviour of calls to malloc() as long as the memory is not initialized (such as by calloc(), or user code).

Matt Joiner
You're right, I was surprised to find that it is specified in the docs for malloc that you linked.
Eloff
A: 

"seemingly random unacceptable latency for very large arrays

You could also consider mlock() or mmap() + MAP_LOCKED to mitigate the impact of paging. Many CPUs support huge (aka large) pages, pages larger than 4kb. These larger pages can mitigate the impact of the TLB on streaming reads/writes.

Brian