malloc function in C programing with 3 example scenarios

(Last Updated On: February 26, 2019)

malloc function in c programing examples interview question based on scenarios – Write programs for following scenarios:

Q-1: Allocate memory dynamically using malloc() function for 1 integer, store value 10 and read it.
Q-2: Create memory block for 10 integers and store and read numbers from 0-9.
Q-3: Copy String from an array char[] =”Hello World” to memory allocated using malloc() function.


Before writing programs for above scenarios, first of all, recommended to read dynamic memory allocation in C. Because, it is really important to know that how dynamic memory is handled. If not handled then we will get memory leak problem. How dynamic allocation is done or programmed. How to use malloc() function in C language and free() function etc.

Answer: All above scenarios are explained here with malloc function in C example program. Also, code documents/ comments are provided.

Program for Scenario -1 using malloc() function:

Program Example for Scenario -2 using C malloc() function:


Program for Scenario -3 using C malloc function: