malloc() Memory Allocation in C Programming
C programming allows you to manage program memory on your own by the function malloc(). The Function malloc is most commonly used to attempt to grab a continuous portion of memory. The malloc() function allocates a memory block of at least size bytes. The block may be larger than size bytes because of space required for alignment and maintenance information. You have to ensure that you have enough memory on your system to allocate memory space. If you have allocated memory using malloc() you should not forget to free() it when no longer requiredmalloc returns a void pointer to the allocated space or NULL if there is insufficient memory available. To return a pointer to a type other than void, use a type cast on the return value.
If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc, even if the amount of memory requested is small
malloc() Memory Allocation Example
#include <stdlib.h>
#define MALLOC_ERROR -1
static void *checked_malloc(const size_t size)
{
void *data;
data = malloc(size);
if (data == NULL)
{
fprintf(stderr, "\nOut of memory.\n");
fflush(stderr);
exit(MALLOC_ERROR);
}
return data;
}
(can be improved with calloc() usage and realloc())
Then, invoke the method with:
char *new_data;
size_t whatever_u_need = 20;
new_data = checked_malloc(whatever_u_need);