linux-sysprog · beginner · ~10 min

Will this allocation fail under the rlimit?

RLIMIT_AS budgeting.

Challenge

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.

Task

Implement int alloc_would_fail(long rlimit_as_bytes, long current_used_bytes, long alloc_bytes) that predicts whether the allocation fits.

Input

  • 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.

Output

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.

Example

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

Edge cases

  • used + alloc == rlimit: exactly fits, returns 0.
  • Any negative argument returns 1.

Why this matters

RLIMIT_AS sets a hard wall on address-space size. Predicting whether a malloc(N) would succeed under that wall trains the intuition.

Input format

Three longs: the RLIMIT_AS cap, the bytes already used, and the bytes to allocate.

Output format

1 if current_used + alloc exceeds the cap (or any input is negative), else 0.

Constraints

Equality fits (returns 0). Any negative input returns 1.

Starter code

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; }

Common mistakes

Forgetting integer overflow on the sum.

Edge cases to handle

Exact boundary (used + alloc == rlimit → OK). Negatives.

Complexity

O(1).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.