Tuesday 11 December 2012

Memory Allocation in C


When an ELF executable is executed, a process is created and its process image is create in the RAM. However, it is here in the process image in RAM, all the variables are assigned memory. Sometimes memory is allocated statically i.e. defined how much memory at the compile time, and at times it has to be allocated dynamically. Where, it is specified at run time the amount of memory needed.

Static Memory Allocation

First of all, please note, static memory allocation is not related to the ‘static’ variables in C programing.
Look at the following statement of a program:

int var = 30;
It is an initialized variable which is of datatype ‘int’ and has been allocated memory of the size of ‘int’ (lets say 4 bytes, which is a standard in Linux). Such kind of memory allocations are called static memory allocations. Note, at compile time we know here that ‘sizeof(int)’ amount of memory will be allocated. Here are some more examples of static memory allocation

char c;
float fvar;
int array[12];
This also explains why arrays take only constants as their sizes.

Worth mentioning, all such static memory allocations take place in the stack of the process image with certain exceptions like uninitialised global variables, const string pointers etc.

Dynamic Memory Allocations

In several cases, we might not know how much memory do we need at the compile-time. Its can only be specified at the run-time based on the value of a certain variable. For example, in the case of linked lists, where a node can be added/deleted at runtime, or matrices of varying rows/columns. For such scenarios, we have dynamic memory allocations. C provides following methods to allocate memory. Dynamic memory allocation always allocates memory in the heap of the process image.

       void *malloc(size_t size);
       void *calloc(size_t nmemb, size_t size);
       void *realloc(void *ptr, size_t size);
1. ‘malloc()’ is used for allocating a specific amount (in bytes) of memory. It returns a pointer to the memory allocated. However, the returned pointer is a void pointer which needs to be type-casted for regular use. It does not initialise the allocated memory. It returns a NULL pointer in case the allocations fails due to any reason. So, one can check for success/failure of this method by checking if the returned pointer is NULL or not. For more such details regarding malloc method, please refer its man page.
ex:
int *ptr = NULL;
int amt = 30;
ptr = (int*) malloc ( amt * sizeof(int));
2. ‘calloc()’ is used for allocating a specific amount of a particle datatype of a memory. Hence, it takes two arguments as one can see in the syntax provided above. ‘calloc()’ also returns the pointer to the allocated chunk of memory, and it also needs the type casting. However, it attempts to initialise all the bits of the allocated memory to zero. It returns a NULL pointer in case the allocations fails due to any reason. For more details on this method, please refer to its man page.
ex:
int *ptr = NULL;
ptr = (int*) malloc ( amt,  sizeof(int));
3. Another method for dynamic memory allocation is ‘realloc()’. The above two methods are there for fresh memory allocations. However, what if one just wants to expand/shrink an already allocated chunk of memory? For such cases we have ‘realloc()’. Depending upon the memory layout, it either just allocates the extra memory demanded or re-allocated the whole requested memory. It behaves similar to ‘malloc()’ as far as memory allocations are concerned.
ex:
int *newPtr = NULL;
newPtr = (int*) realloc (ptr, amt + extra);
Note, ‘realloc()’ can also do fresh allocation of memory if the input pointer is a NULL.

Freeing up

Power comes with responsibility. Since C gives you the power to use and allocated memory as per our needs, hence it is the onus of the programmer to take care of allocated and free memory. Hence, freeing up of allocated memory is very essential in C programming and avoids many vulnerabilities.

All the statically allocated memory is free-ed automatically as its scope ends. However, the dynamically allocated memory have to be free-ed by the programmer. Here is the method which is used to free memory allocated on heap.
ex:
void free(void *ptr);

A complete example implementation


#include <stdio.h>
#include <stdlib.h>

int main()
{
    int size = 15; //static memory allocation
    int i; //static memory allocation
    int *mptr = NULL; 
    int *cptr = NULL;

    //Using malloc
    mptr = (int*) malloc (size *sizeof(int)); //dynamic memory allocation
    if (mptr == NULL)
    {
         printf("Error in  memory allocation\n");
    }
    else
    {
        printf("Use new chunk of memory\n");
        for (i = 0; i < size; i++)
        {
            mptr[i] = i;
        }
    }

    //Using calloc
    cptr = (int*) calloc (size, sizeof(int)); //dynamic memory allocation
    if (cptr == NULL)
    {
         printf("Error in  memory allocation\n");
    }
    else
    {
        printf("Use new chunk of memory\n");
        for (i = 0; i < size; i++)
        {
            cptr[i] = i;
        }
    }

    //Using realloc
    size += size; //Increase size
    mptr = (int*) realloc (mptr, size * sizeof(int)); //extend the dynamic memory allocation
    if (mptr == NULL)
    {
         printf("Error in  memory allocation\n");
    }
    else
    {
        printf("Use new chunk of memory\n");
        for (i = 0; i < size; i++)
        {
            mptr[i] = i;
        }
    }

    //Free-ing up memory
    if (cptr)
        free(cptr);
    cptr = NULL;
    if (mptr)
        free(mptr);
    mptr = NULL;
    // No need to free size and i
    
    return 0;
}


- Gaurav Singhal

No comments:

Post a Comment