10 Questions on dynamic memory allocation in C

interview question on dynamic memory allocation in c

At the beginning of the career, many developers fear to use dynamic memory allocation. In this article, I will explain 10 interview questions on dynamic memory allocation C.

If you are looking for interview questions on dynamic memory allocation C or tricky interview questions on memory allocation in c, then you are at the right place. Here I have created the top 10 interview questions on dynamic memory allocation C with answers which might ask by your interviewer in C interviews. So, I hope these interview questions on dynamic memory allocation in C will be helpful for you. So finally Best of Luck.

If you are new and want to learn dynamic memory allocation in C from basic, then you can check the below articles on dynamic memory allocation.

Click Here, Introduction of dynamic memory allocation in C.

Besides that, if you have any other doubts regarding the memory management function, feel free to send an email to me or you can comment in the comment box. We will try to solve your problem as soon as possible.

 

Q) What is the difference between malloc and calloc?

A malloc and calloc are memory management functions. They are used to allocate memory dynamically. Basically, there is no actual difference between calloc and malloc except that the memory that is allocated by calloc is initialized with 0. In C language,calloc function initialize the all allocated space bits with zero but malloc does not initialize the allocated memory. These both function also has a difference regarding their number of arguments, malloc takes one argument but calloc takes two.

 

Q) Is it better to use malloc () or calloc ()?

The calloc function initialize the allocated memory with 0 but malloc don’t. So the memory which is allocated by the malloc has the garbage data. In another word you can say that calloc is equal to the combination of malloc and memeset.

See the below expression,

ptr = calloc(nmember, size);  //is essentially equivalent to

ptr = malloc(nmember * size);
memset(ptr, 0, (nmember * size));

 

Note: If you don’t want to initialize the allocated memory with zero, It would be better to use malloc over calloc.

 

Q) How can you determine the size of an allocated portion of memory?

In C language, we can calculate the size of the static array using the sizeof operator but there is no operator to calculate the size of the dynamically allocated memory. So using some trick we can get the size of the allocated array. Mainly there are two ways to get the size of allocated memory in every section of the code.

  • Create a global variable to store the size of the allocated memory.
  • Carry the length of allocated memory.

Let see an example code, where I am explaining how you can carry the length of the array. So suppose you need to create an integer array whose size is n. So to carry the array length of the array, you need to allocate the memory for n+1.

int *piArray = malloc ( sizeof(int) * (n+1) );

 

If memory is allocated successfully, assign n (size of the array) its 0 places.

piArray[0] = n;
     or
* piArray = n;

 

Now it’s time to create a copy of the original pointer but to left one location from the beginning.

//Left 0th location
int * pTmpArray = piArray +1;

 

Note: if you are new, see this article arithmetic operation on the pointer.

 

Now, whenever in a program you require the size of the allocated dynamic, you get from the temporary pointer(copy pointer).

//Getting size of the allocated array
int ArraySize = pTmpArray[-1];

 

After using the allocated memory don’t forget to deallocate the allocated memory.

free (piArray);

 

 

Q) What is the purpose of realloc( )?

The realloc function is used to resize the allocated block of the memory. It takes two arguments first one is a pointer to previously allocated memory and the second one is the newly requested size. The realloc function first deallocates the old object and allocates again with the newly specified size. If the new size is lesser than the old size, the contents of the newly allocated memory will be the same as prior but if any bytes in the newly created object goes beyond the old size, the values of the object will be indeterminate.

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

int main ()
{
    char *pcBuffer = NULL;

    /* Initial memory allocation */
    pcBuffer = malloc(8);

    strcpy(pcBuffer, "aticle");

    printf("pcBuffer = %s\n", pcBuffer);

    /* Reallocating memory */
    pcBuffer = realloc(pcBuffer, 15);

    strcat(pcBuffer, "world");

    printf("pcBuffer = %s\n", pcBuffer);

    free(pcBuffer);

    return 0;
}

Output:

pcBuffer = aticle
pcBuffer = aticleworld

Note: It should only be used for dynamically allocated memory but if ptr is the null pointer, realloc behaves like the malloc function.

For learning more, you can signup for the free trial of this popular c video course by Kenny Kerr.

Q) What is static memory allocation and dynamic memory allocation?

According to C standard, there are four storage duration, static, thread (C11), automatic, and allocated. The storage duration determines the lifetime of the object.

The static memory allocation:

Static Allocation means, an object has external or internal linkage or declared with static storage-class. It’s initialized only once, prior to program startup and its lifetime is throughout the execution of the program. A global and static variable is an example of static memory allocation.

The dynamic memory allocation:

In C language, there are a lot of library functions (malloc, calloc, or realloc,..) which are used to allocate memory dynamically. One of the problems with dynamically allocated memory is that it is not destroyed by the compiler itself that means it is the responsibility of the user to deallocate the allocated memory.

When we allocate the memory using the memory management function, they return a pointer to the allocated memory block and the returned pointer is pointing to the beginning address of the memory block. If there is no space available, these functions return a null pointer.

 

Q) What is the return value of malloc (0)?

If the size of the requested space is zero, the behavior will be implementation-defined. The return value of the malloc could be a null pointer or it shows the behavior like that size is some nonzero value. So you must never use the malloc(0) in your C program.

Let see an example C program, where I am allocating memory using the malloc with size 0

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


int main (void)
{
    int *piBuffer = NULL;

    //allocating memory using
    //the malloc with size 0.
    piBuffer = malloc(0);

    //make sure piBuffer is valid or not
    if (piBuffer == NULL)
    {
        // allocation failed, exit from the program
        fprintf(stderr, "Out of memory!\n");
        exit(1);
    }

    *piBuffer = 10;

    printf("%d\n",*piBuffer);

    free(piBuffer);

    return 0;
}

Output: Implementation-dependent.

 

 

Q) What is the memory leak in C?

A memory leak is a common and dangerous problem. It is a type of resource leak. In C language, a memory leak occurs when you allocate a block of memory using the memory management function and forget to release it.

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

int main ()
{
    char * pBuffer = malloc(sizeof(char) * 20);

    /* Do some work */

    return 0; /*Not freeing the allocated memory*/
}

 

Note: once you allocate a memory than allocated memory does not allocate to another program or process until it gets free.

For more detail see this article, Problem with dynamic memory allocation

 

Q) What is dynamic memory fragmentation?

The memory management function gives the guaranteed that allocated memory would be aligned with the object. The fundamental alignment is less than or equal to the largest alignment that’s supported by the implementation without an alignment specification.

One of the major problems with dynamic memory allocation is fragmentation, basically, fragmentation occurred when the user does not use the memory efficiently. There are two types of fragmentation, external fragmentation, and internal fragmentation.

The external fragmentation is due to the small free blocks of memory (small memory hole) that are available on the free list but the program not able to use it. There are different types of free list allocation algorithms that used the free memory block efficiently.

Consider a scenario where the program has 3 contiguous blocks of memory and the user frees the middle block of memory. In that scenario, you will not get a memory, if the required block is larger than a single block of memory. See the below Image,

External Fragmentation

The internal fragmentation is the wastage of memory that is allocated for rounding up the allocated memory and in bookkeeping (infrastructure). The bookkeeping memory is used to keep the information of allocated memory.

Whenever we called malloc function then it reserves some extra bytes (depend on implementation and system) for bookkeeping. This extra byte is reserved for each call of malloc and becomes a cause of the internal fragmentation.

Let see an example program to understand the internal fragmentation,

In the below code, a programmer may think that the system will allocate 8 *100 (800) bytes of memory but due to bookkeeping, (if bookkeeping bytes is 8) system will allocate 8*100 extra bytes. You can see how internal fragmentation is waisting the heap memory. This is only for understanding actual behavior is the implementation-dependent.

char *acBuffer[100];

int main()
{
    int iLoop = 0;

    while(iLoop < 100)
    {
        acBuffer[iLoop ] =  malloc(8);

        ++iLoop

    }
}

 

 Q) How is free work?

When we call the memory management functions (malloc, calloc or realloc) then these functions keep extra bytes for bookkeeping. Whenever we call the free function and pass the pointer that is pointing to allocated memory, the free function gets the bookkeeping information and release the allocated memory. Anyhow if you or your program change the value of the pointer that is pointing to the allocated address, the calling of the free function gives the undefined result.

  
 ____ The allocated block ____
/                             \
+--------+--------------------+
| Header | Your data area ... |
+--------+--------------------+
         ^
         |
       +-- Returned Address

 

Let us see a program to understand the above concept. The behavior of the below program is not defined.

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

int main()
{
    char *pcBuffer = NULL;
    //Allocate the memory
    pcBuffer  =  malloc(sizeof(char) *  16);

    //make sure piBuffer is valid or not
    if (pcBuffer == NULL)
    {
        // allocation failed, exit from the program
        fprintf(stderr, "Out of memory!\n");
        exit(1);
    }
    //Increment the pointer
    pcBuffer++;
    //Call free function to release the allocated memory
    free(pcBuffer);

    return 0;
}

OutPut: Undefined Result

 

Q) What is a dangling pointer?

Generally, dangling pointers arise when the referencing object is deleted or deallocated, without changing the value of the pointers. It creates the problem because the pointer is still pointing the memory that is not available. When the user tries to dereference the daggling pointers than it shows the undefined behavior and can be the cause of the segmentation fault.

In simple words, we can say that dangling pointer is a pointer that not pointing a valid object of the appropriate type and it can be the cause of the undefined behavior.

Let’s see the below image for a better understanding.

In the image Pointer1 and Pointer2 is pointing to a valid object but Pointer3 is pointing an object that has been already deallocated. So Pointer3 becomes a dangling pointer when you will try to access the Pointer3 than you will get the undefined result or segmentation fault.

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

int main()
{
    int *piData = NULL;

    //creating integer of size 10.
    piData = malloc(sizeof(int)* 10);
    //make sure piBuffer is valid or not
    if (piData == NULL)
    {
        // allocation failed, exit from the program
        fprintf(stderr, "Out of memory!\n");
        exit(1);
    }
    free(piData); //free the allocated memory

    *piData = 10; //piData is dangling pointer

    printf("%d\n",*piData);

    return 0;
}

Output: undefined.

I have tried to collect mostly basic interview questions related to dynamic memory allocation and deallocation. I hope these interview questions on dynamic memory allocation will helpful. But it is my request if you have any points to improve this article, please let me know.  If you want to add something in this Artice, then please write comment in comment box or send me an email.

Recommended Articles for you:

71 comments

  1. Nice Article.
    Is there any way to print allocated dynamic memory block header ? I know that is maintained by memory management functions.

  2. “The calloc function first deallocates the old object and allocates again with the newly specified size. ”

    I think it should be realloc ,may be a typo

Leave a Reply

Your email address will not be published. Required fields are marked *