Memory allocation in c

Memory allocation in c

It is a function which is used to allocate a block of memory dynamically. It reserves memory space of specified size and returns the null pointer pointing to the memory location. The pointer returned is usually of type void. … The malloc function returns a pointer to the allocated memory of byte_size.

Memory allocation Flow

memory allocation in c language AndroWep-Tutorials
memory allocation in c language AndroWep-Tutorials

The malloc() function

The malloc() function is one of C’s memory allocation functions. When you call malloc(), you pass it the number of bytes of memory needed. malloc() finds and reserves a block of memory of the required size and returns the address of the first byte in the block.

#include <stdlib.h> 
void *malloc(size_t size);

malloc() allocates a block of memory that is the number of bytes stated in size. By allocating memory as needed with malloc() instead of all at once when a program starts, you can use a computer’s memory more efficiently.

Example 1

#include <stdlib.h>
#include <stdio.h> 
int main( void ) { 
/* allocate memory for a 100-character string */ 
       char *str; str = (char *) malloc(100);
       if (str == NULL) {
            printf( “Not enough memory to allocate buffer\n”); exit(1); 
          } 
            printf( “String was allocated!\n” );
        return 0;
}

Example 2

/* allocate memory for an array of 50 integers */ 
int *numbers;
numbers = (int *) malloc(50 * sizeof(int)); 

Example 3

/* allocate memory for an array of 10 float values */
float *numbers;
numbers = (float *) malloc(10 * sizeof(float)); 

Why do we need to allocate memory in C?

“free” method is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() are not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.

What are the types of memory allocation?

There are two types of memory allocation. 1) Static memory allocation — allocated by the compiler. Exact size and type of memory must be known at compile time. 2) Dynamic memory allocation — memory allocated during run time.