Memory Management in C

In this article I would like to provide few tips related to memory management when we use C libraries malloc(), calloc() and free() functions.

Whenever possible, try to use static buffers where compiler automatically frees such memory. Make sure that, previously allocated memory is freed manually.

malloc():

The library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which de-allocates the memory so that it can be used for other purposes.

Recommended:   C Program to Sort an Array in Descending Order Using Bubble Sort

When you are allocating memory using malloc, make sure that that 0 (zero) bytes are not allocated. According to the documentation, behaviour for malloc() for this case is undefined. Always check for the pointer to the memory returned by calloc/malloc. If this pointer is NULL then the memory allocation should be considered unsuccessful and no operations should be performed using that pointer.

free():

The library function free(void *ptr) de-allocates the memory previously allocated by a call to calloc, malloc, or realloc.



#include 

int main()
{
    
    int no_emements, i, *ptr, sum = 0;

    printf("\n\nEnter number of elements: ");
    scanf("%d", &no_elements);

    // dynamic memory allocation using malloc()
    ptr = (int *) malloc(no_emements*sizeof(int));

    if(ptr == NULL) // if empty array
    {
        printf("\n\nError! Memory not allocated\n");
        return 0;   // exit from program
    }

    printf("\n\nEnter elements of array: \n\n");
    for(i = 0; i < no_elements; i++)
    {
        // storing elements at contiguous memory locations
        scanf("%d", ptr+i);    
        sum = sum + *(ptr + i);
    }

    // printing the array elements using pointer to the location
    printf("\n\nThe elements of the array are: ");
    for(i = 0; i < no_elements; i++)
    {
        printf("%d  ",ptr[i]);    // ptr[i] is same as *(ptr + i)
    }

    /* 
        freeing memory of ptr allocated by malloc 
        using the free() method

    */
    free(ptr);

    return 0;
}


Check and run the program here:

You can run the above program on codeboard editor and see the results. You are allowed to modify code and run. In the editor there is a menu at the top-right corner. Here you can see two buttons such as ‘Compile’ and ‘Run’.

Share this:

Tags:

1 Comment
  1. Excellent article. Keep writing such kind of info on your site.

    Im really impressed by your site.
    Hey there, You’ve performed a fantastic job.

    I’ll definitely digg it and personally suggest to my friends.
    I’m sure they will be benefited from this web site.

Leave a reply

Troubleshootyourself
Logo