More malloc & free - Advanced Memory Allocation
This section covers advanced memory allocation techniques including error-handling wrappers, zero-initialized allocation, memory reallocation, and complex allocation patterns.Function Prototypes
Error-Handling Allocation
malloc_checked() - Guaranteed Allocation
- Critical allocations where failure is unrecoverable
- Simplifying code when NULL checks are verbose
- Programs that must allocate or die
Advanced String Operations
string_nconcat() - Concatenate with Limit
- NULL safety: Treats
NULLas empty string - Limit handling: Uses at most
nbytes froms2 - Smart sizing: If
n >= len(s2), uses entires2 - Proper allocation:
len(s1) + min(n, len(s2)) + 1
This function is safer than
strcat because:- Creates new string (doesn’t modify inputs)
- Limits bytes from
s2(prevents overflow) - Handles NULL inputs gracefully
- Always null-terminates result
Zero-Initialized Allocation
_calloc() - Clear Allocation
| Feature | malloc | calloc |
|---|---|---|
| Parameters | Size in bytes | Number of elements + size each |
| Initialization | Uninitialized (garbage) | Zero-initialized |
| Use case | Any allocation | Arrays, structures |
| Speed | Faster (no initialization) | Slower (zeros memory) |
-
Arrays that need zero initialization
-
Bit flags and boolean arrays
-
Preventing uninitialized memory bugs
-
Security-sensitive data
Array Generation
array_range() - Create Integer Range
- Creates array containing integers from
mintomax(inclusive) - Automatically calculates array size:
max - min + 1 - Uses
sizeof(*ar)for type-safe allocation
Why
sizeof(*ar) instead of sizeof(int)?Memory Reallocation
While not shown in the source files provided,realloc is a crucial function:
realloc() - Resize Allocated Memory
- Resizes existing allocation
- Preserves data (up to minimum of old/new size)
- May move memory to new location
- Returns new pointer (may differ from
ptr)
Advanced Patterns
Dynamic String Builder
Memory Pool
Debugging and Optimization
Memory Usage Tracking
Performance Tips
-
Batch allocations when possible
-
Use calloc only when needed
-
Realloc geometrically
Key Takeaways
malloc_checkedsimplifies error handling but should be used judiciouslycalloczeros memory - use for arrays, structures, and securitycalloc(n, size)can overflow - validate inputsstring_nconcatsafely limits concatenation lengtharray_rangedemonstrates type-safe allocation withsizeof(*ptr)realloccan move memory - always use temporary pointer- Never use old pointer after
reallocwithout checking - Track allocations and frees to detect leaks
- Batch allocations for better performance
- Use geometric growth for dynamic arrays
- Free in reverse order of allocation for complex structures