r/cprogramming • u/Apprehensive-Trip850 • Apr 29 '26
Can on demand paging be used to implement dynamic arrays?
Dynamic arrays, for instance std::vector in c++ are implemented based on the idea that if their size exceeds their capacity, the underlying array is reallocated to one that is twice the current capacity.
My question is, would this even be necessary given that at least in Linux, pages are allocated to a process on demand?
For instance, with a simple program like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
long size = (long)(64 * 4096 * 64) * 8;
long *arr = malloc(size);
for(long i=0; i < (size/32); i++)
{
arr[i] = i;
printf("%d\n", arr[i]);
}
printf("--->%p\n", arr);
while(1)
;
}
if size were equal to 64 * 4096 * 64, we can see via /proc/[PID]/maps that the heap section is about 4M(despite the malloc being for 16M) and with the size given in the program it is about 32M(despite the malloc being for 128M), illustrating on demand paging.
Considering that this implementation is probably not used widely, why is that? I figured one explanation would be the assumption of the system having on demand paging at all, which simply might not be the case, thus reducing portability, but what am I missing otherwise?
5
u/dkopgerpgdolfg Apr 29 '26 edited Apr 29 '26
If we think for a moment about writing assembly and calling syscalls directly:
With functions like mmap (mremap etc., the whole group), madvise, faultfd/signalfd, ebpf, etc., ... you're right, actual reallocations (that might include moving the data etc.) can mostly be avoided, and there are many other nice things possible.
Where it gets problematic are the language specs of C and C++, that are much more limiting and ambiguous.
Like, in a simple case and ignoring the ideas above, surely you know that you can't allocate 10 ints with malloc and the access [12] in that array - it's past the end of the allocation, therefore UB. This is true even if, right after that first array, another allocated array happens to be, with no gap between them. Ie. C happens to define that one malloc call will always give you a single array, that you can legally access from the first to last element (independent of what happens within malloc), but you can't really view two mallocs as mergeable even if the addresses it gave you would make this possible.
If you now start doing some syscall magic to make your self-allocated array larger, you're a) firmly outside the C standard (it doesn't even know mmap), b) you have to know how much your C implementation (compiler optimizations, glibc allocator system, ...) will forgive you, or if you're introducing code that might cause problems in some way.
4
u/PearMyPie Apr 29 '26
Paging is completely unknown to the user process.
A user process works with its own virtual address space, and the operating system manipulates memory pages completely unknown to the program.
2
u/weregod Apr 29 '26
If you want to preallocate huge buffers for thousands of small arrays it will likely be slower than small buffers. If you want few big long living arrays your allocating huge buffers can be fine. calloc might work better then malloc in some cases (page will be allocated on write). You should always check *alloc result for NULL especially when requesting big chunk of memory. Don't assume overcommit.
1
u/freaxje Apr 29 '26
The decision where your heap ends (the brk() location) was made by your libc, not by the Linux kernel. It represents ~ your VmSize (on Linux), not your VmRSS. What you are referring to as 'on demand paging' has more to do with VmRSS than with VmSize.
ps. std::vector<T> is C++, not C. You have Reddit channels for C++ questions.
1
u/ifknot Apr 29 '26
This is a confusing question the example is C the question seems to be about C++ std vector the idea seems to be an arena/region based memory management instead of trusting the compiler?
1
u/Revolutionary_Ad7262 Apr 29 '26
Vast majority of allocations are small and this trick does not work. Also it is quite platform specific. For a different size of pages (like huge pages) you could get different results
Also the upfront reserving is just good and always optimal
1
u/WittyStick Apr 29 '26 edited Apr 29 '26
A call to
mmapcan specifyMAP_NORESERVE, which won't reserve any swap space for the allocation until it is accessed, in which case, the kernel will allocate a page, unless there is insufficient physical and you'll get aSIGSEGV.In general, such behavior is undesirable. We would want to know that insufficient memory is available at the time of calling
mmap, rather than finding out later.See also the discuesson of
/proc/sys/vm/overcommit_memoryin proc_sys_vm(5).In regards to dynamic arrays, the doubling strategy is only one option - one that is simple to implement and which we can also avoid storing a
capacityfield in the array header because we can compute it on demand withcapactity = __builtin_stdc_bit_ceil(length).Various other dynamic arrays use other strategies. Some examples (see also Growth factor):
Golang's starts at
length*2, but after the array reaches a certain point, it reduces tolength*1.25.Java uses
length*1.5, which is better for reusing memory. There's an argument that the ideal growth rate is the golden ratio,length*1.618..., and this is close to this but simpler to implement.The constant factor growth still wastes
O(n)space, because we ignore constant factors in analysis.Another approach can scale the array by
length * (1 + 1/√length)=length + √length. This is a good choice for memory constrained systems, as onlyO(√n)space is wasted in the worst case - but it also results inO(√n)total calls to the allocator, whereas the constant growth rate allocators haveO(log n)allocator calls.See comparison of
O(n),O(√n)andO(log n).Of course we wouldn't use an actual
sqrtoperation for this, but the approximate:The sqrt growth rate is used by HAT and RAOTS, but these don't allocate a contiguous array - they use an index block of size
√nwith pointers to data blocks - in HAT's case, every block is also√n(which results in a lot of shuffling memory), whereas in RAOTS the blocks are varying power of 2 sizes, starting smaller and growing with the array, which reuses most of the existing allocations and can use stable pointers - and we can also avoid storingcapacityin the header as it can be computed from length similar to the doubling strategy.1
u/dfx_dj Apr 30 '26
You're not seeing this allocation counted towards the "heap" of the process because (most likely)
mallocdecided to satisfy the allocation through an anonymousmmap.It's actually quite common to do this as a platform-specific optimisation, but in most cases you'd see the code do a
mmapdirectly instead of doing it throughmalloc. Reason being that this is neither portable (mmapitself might be to a certain extent, but the underlying semantics are not), nor canmallocbe reliably expected to do allocations in a specific way.0
u/This_Growth2898 Apr 29 '26
Read about virtual memory