testing-debugging · intermediate · ~15 min
Enforce allocation size quotas defensively and handle memory allocation failures safely.
Unchecked malloc calls can cause denial of service or remote code execution when memory limits are exceeded. Robust software applies memory quotas and checks for multiplication overflow (nmemb * size) before requesting memory.
Implement:
void *safe_calloc_quota(size_t nmemb, size_t size, size_t *quota_remaining);
void safe_free_quota(void *ptr, size_t bytes, size_t *quota_remaining);
safe_calloc_quota:quota_remaining == NULL, nmemb == 0, or size == 0, return NULL.nmemb > SIZE_MAX / size, return NULL.total = nmemb * size.total > *quota_remaining, return NULL without modifying *quota_remaining.calloc(nmemb, size).total from *quota_remaining and return the pointer.NULL and do not modify *quota_remaining.safe_free_quota:ptr != NULL and quota_remaining != NULL:ptr.bytes back to *quota_remaining.size_t quota = 1000;
int *p = safe_calloc_quota(10, sizeof(int), "a); // 40 bytes deducted, quota == 960
safe_free_quota(p, 10 * sizeof(int), "a); // 40 bytes restored, quota == 1000
nmemb: element count; size: element size; quota_remaining: pointer to available bytes.
Returns allocated pointer or NULL on quota/overflow error.
Check size_t overflow before multiplication. Atomic quota update.
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
/* Allocate zeroed memory within quota limits. Return NULL on error or quota exceeded. */
void *safe_calloc_quota(size_t nmemb, size_t size, size_t *quota_remaining) {
(void)nmemb; (void)size; (void)quota_remaining;
return NULL;
}
/* Free allocated memory and credit bytes back to quota. */
void safe_free_quota(void *ptr, size_t bytes, size_t *quota_remaining) {
(void)ptr; (void)bytes; (void)quota_remaining;
}
Deducting from quota before verifying allocation success; forgetting to check multiplication overflow.
Overflowing nmemb * size returns NULL; exact quota match succeeds; freeing NULL does nothing.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.