malloc function in c programming 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 issue. 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:
int main()
{
int *ptr = NULL;
/*Dynamically allocate memory for 1 integer
* Use sizeof() operator to get size of integer.
* Typecast returned void pointer by malloc to int.
*/
ptr = (int *)malloc(sizeof(int));
if (ptr == NULL)
{
printf("ERROR: memory allocatin fail\n");
//return from here and process further
return 1;
}
//Assign int value to allocated memory.
*ptr = 10;
// Read value from allocated memory and
// display on console
printf("%d\n", *ptr);
//Free allocated memory
free(ptr);
return 0;
}
Program Example for Scenario -2 using C malloc() function:
int main()
{
int *ptr = NULL;
int i = 0;
//Dynamically allocate memory bloc for 20 integers
//Memory size = 10 integers multiplied by
//size of one integer i.e. sizeof(int)
ptr = (int *)malloc(10*sizeof(int));
if (ptr == NULL)
{
printf("ERROR: memory allocatin fail\n");
return 1;
}
//Assing 0-9 numbers in memory space
for (i = 0; i < 10; i++) {
ptr[i] = i;
}
//Read numbers from memory space
for ( i = 0; i < 10; i++) {
printf("%d\n", ptr[i]);
}
//Free allocated memory
free(ptr);
return 0;
}
Program for Scenario -3 using C malloc function:
int main()
{
char *str = NULL;
char arr_str[] ="Hello World";
//Get the length of the string to for
//dynamic memory allocation.
//Add extra 1 for '\0' ending string in c.
int len = strlen(arr_str)+1;
//Allocate memory equal to len+1.
//+1 because of '\0' ending string in c.
str = (char *) malloc(len*sizeof(char));
if (str == NULL)
{
printf("ERROR: memory allocatin fail\n");
return 1;
}
//Copy arr string into dynamically allocated memory.
strcpy(str, arr_str);
//display the string from dynamic memory
printf("String = %s",str);
free(str);
return(0);
}