Memory API in UNIX/C
Memory API in UNIX/C
The memory API in UNIX/C provides functions that allow programs to allocate, use, resize, and free memory during execution. Proper memory management is essential for building reliable and bug-free software.
1. Types of Memory in C Programs
A. Stack Memory (Automatic Memory)
-
Managed automatically by the compiler.
-
Used for:
-
Local variables
-
Function parameters
-
Return values
-
-
Allocated when a function is called and freed when it returns.
-
Short-lived: data does not persist after the function exits.
Example
B. Heap Memory (Dynamic Memory)
-
Managed explicitly by the programmer.
-
Used when memory must persist beyond function calls.
-
Requires manual allocation and deallocation.
Example
2. Core Memory Allocation Functions
malloc(size_t size)
-
Allocates
sizebytes on the heap. -
Returns:
-
Pointer to allocated memory on success
-
NULLon failure
-
-
Include:
Best practice
-
sizeof()ensures correct allocation size.
*free(void ptr)
-
Releases heap memory previously allocated with
malloc(). -
Prevents memory leaks.
Example
3. Other Useful Memory Functions
calloc()
-
Allocates memory and initializes it to zero.
-
Helps avoid uninitialized data bugs.
realloc()
-
Resizes previously allocated memory.
-
May move data to a new location and copy old contents.
mmap()
-
Requests memory directly from the OS.
-
Can create anonymous memory regions, uses swap space (not tied to files).
-
Used internally by memory allocators or advanced programs.
4. OS Support Behind the Scenes
-
malloc()andfree()are library calls, not system calls. -
Internally they may use:
-
brk/sbrk → change heap size
-
mmap() → obtain additional memory from OS
-
Programmers should not directly call brk/sbrk.
5. Common Memory Programming Errors
1. Forgetting to Allocate Memory
2. Not Allocating Enough Memory (Buffer Overflow)
3. Using Uninitialized Memory
-
Allocated memory may contain random data.
-
Must initialize before use.
4. Memory Leak
-
Forgetting to call
free(). -
Causes memory usage to grow over time.
5. Dangling Pointer
-
Using memory after it has been freed.
6. Double Free
-
Freeing the same memory twice.
-
Leads to undefined behavior or crashes.
7. Invalid Free
-
Passing a pointer not returned by
malloc()tofree().
6. Debugging Tools
Tools exist to detect memory issues:
-
Valgrind
-
Purify
They help identify leaks, invalid accesses, and misuse.
7. Key Takeaway
-
Stack → automatic, short-lived, compiler managed
-
Heap → manual, flexible, programmer managed
-
malloc/free → primary memory API functions
-
Careless usage leads to crashes, leaks, or security bugs.
Comments
Post a Comment