linux-sysprog · beginner · ~10 min
RLIMIT_AS budgeting.
Decide whether an allocation would push a process over its address-space limit (RLIMIT_AS). This is a pure budget check — no memory is allocated.
Implement int alloc_would_fail(long rlimit_as_bytes, long current_used_bytes, long alloc_bytes) that predicts whether the allocation fits.
rlimit_as_bytes: the hard cap on total address space, in bytes.current_used_bytes: how much is already in use.alloc_bytes: the size of the new allocation.Returns 1 if the allocation would exceed the limit (current_used + alloc > rlimit_as), else 0. Any negative input is treated defensively as a failure and returns 1.
alloc_would_fail(128MB, 100MB, 50MB) -> 1 (150MB > 128MB)
alloc_would_fail(128MB, 100MB, 28MB) -> 0 (exactly at the cap, fits)
alloc_would_fail(128MB, 100MB, 27MB) -> 0
alloc_would_fail(-1, 0, 0) -> 1 (negative input -> refuse)
alloc_would_fail(128, 0, -1) -> 1
used + alloc == rlimit: exactly fits, returns 0.1.RLIMIT_AS sets a hard wall on address-space size. Predicting whether a malloc(N) would succeed under that wall trains the intuition.
Three longs: the RLIMIT_AS cap, the bytes already used, and the bytes to allocate.
1 if current_used + alloc exceeds the cap (or any input is negative), else 0.
Equality fits (returns 0). Any negative input returns 1.
int alloc_would_fail(long rlimit_as_bytes, long current_used_bytes, long alloc_bytes) { /* TODO */ (void)rlimit_as_bytes; (void)current_used_bytes; (void)alloc_bytes; return 0; }
Forgetting integer overflow on the sum.
Exact boundary (used + alloc == rlimit → OK). Negatives.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.