C Programming - Dynamic Memory allocation:
Dynamic Memory Allocation:
malloc, calloc, or realloc are the three functions used to manipulate memory. These commonly used functions are available through the stdlib library so you must include this library in order to use them.
#include stdlib.h
Dynamic Memory Allocation Process:
When a program executes, the operating system gives it a stack and a heap to work with. The stack is where global variables, static variables, and functions and their locally defined variables reside. The heap is a free section for the program to use for allocating memory at runtime.Allocating a Block of Memory
Use the malloc function to allocate a block of memory for a variable. If there is not enough memory available, malloc will return NULL.The prototype for malloc is:
void *malloc(size_t size);
Do not worry about the size of your variable, there is a nice and convenient function that will find it for you, called sizeof. Most calls to malloc will look like the following example:
ptr = (struct mystruct*)malloc(sizeof(struct mystruct));
This way you can get memory for your structure variable without having to know exacly how much to allocate for all its members as well.
Allocating Multiple Blocks of Memory:
You can also ask for multiple blocks of memory with the calloc function:void *calloc(size_t num, size_t size);
If you want to allocate a block for a 10 char array, you can do this:
- char *ptr;
- ptr = (char *)calloc(10, sizeof(char));
Releasing the Used Space:
All calls to the memory allocating functions discussed here, need to have the memory explicitly freed when no longer in use to prevent memory leaks. Just remember that for every call to an *alloc function you must have a corresponding call to free.The function call to explicitly free the memory is very simple and is written as shown here below:
free(ptr);
To Alter the Size of Allocated Memory
Lets get to that third memory allocation function, realloc.
void *realloc(void *ptr, size_t size);
No comments:
Post a Comment