Dynamic memory allocation in C
The process of allocating memory at runtime is known as dynamic memory allocation.
Sometime applications(software) requires allocation of memory at runtime as per the requirement or need, so C programming have a provision for dynamic memory allocation on heap memory area using some library function.
The C programming language provides several functions for memory allocation and management. These functions can be found in the <stdlib.h> header file.
|malloc( )||allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated space|
|calloc( )||allocates space for an array of elements, initialize them to zero and then returns a void pointer to the memory|
|free( )||This function release a block of memory block specified by address.|
|realloc( )||This function re-allocates memory extending it upto newsize.|
void *malloc(int num);
This function allocates the number of bytes required at runtime and provides the base address of those uninitialized memory as void pointer. Here, size represents the size of memory in byte(s)
float *p; //allocate 12 bytes i.e //3 float blocks p = (float*)malloc(12); OR p = (float*)malloc(3*sizeof(float));
void* calloc(int num,element-size):
This function allocates the number of bytes required at runtime and provides the base address of those initialized memory as void pointer. Here, num represent the number of block(s) required, and size represents the size of block in byte(s).
int *p; //5 integer blocks p = (int*)calloc(5,sizeof(int));
void* realloc(void *p,newsize)
This function re-allocates memory extending it upto newsize. Here, p represent the address need to reallocate with new size, and newsize represents the new size of memory in byte(s).
int *p; //allocates 6 bytes p = (int*)malloc(6); //extends p's memory 6 to 10 p = (int*)realloc(p,10);
This function free the dynamically allocated memory. Here, p represent the address need to be free.
int *p; //allocates 6 bytes p = (int*)malloc(6); //after use need to free free(p);
Difference between malloc() and calloc() :
The only difference between malloc() and calloc() is that, malloc() initializes the allocated memory with garbage values while calloc() initializes the allocated memory with 0 value.
Next topic is file handling in C
Training For College Campus
We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.
Please mail your requirement at email@example.com
Projects For Students
Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.
Students can mail requirement at firstname.lastname@example.org