Introduction
Program in c performs dynamic memory allocation via a group of functions. Here in this article, we will see what are the functions the c programming language uses for dynamic memory allocation in c.
Getting Started
C dynamic memory allocation refers to performing manual memory management for dynamic memory allocation in the C programming language via a group of functions in the C standard library, namely malloc, realloc, calloc and free.
malloc()
The malloc function allocates a memory block of at least size bytes. The block may be larger than size bytes because of the space that's required for alignment and maintenance information.
realloc()
The realloc function changes the size of an allocated memory block. The memblock argument points to the beginning of the memory block. If memblock is NULL, realloc behaves the same way as malloc and allocates a new block of size bytes. If memblock is not NULL, it should be a pointer returned by a previous call to calloc, malloc, or realloc.
The size argument gives the new size of the block, in bytes. The contents of the block are unchanged up to the shorter of the new and old sizes, although the new block can be in a different location. Because the new block can be in a new memory location, the pointer returned by realloc is not guaranteed to be the pointer passed through the memblock argument. realloc does not zero newly allocated memory in the case of buffer growth.
calloc()
The calloc function allocates storage space for an array of number elements, each of length size bytes. Each element is initialized to 0.
free()
The free function deallocates a memory block (memblock) that was previously allocated by a call to calloc, malloc, or realloc. The number of freed bytes is equivalent to the number of bytes requested when the block was allocated (or reallocated, in the case of realloc). If memblock is NULL, the pointer is ignored and free immediately returns. Attempting to free an invalid pointer (a pointer to a memory block that was not allocated by calloc, malloc, or realloc) may affect subsequent allocation requests and cause errors.
Summary
In the above, we got to know a little about the four-measure functions(malloc, realloc, calloc and free) which the C language uses for memory allocation in C. I hope you have enjoyed it a lot.
Thanks