# Exercise: Questions on Dynamic Memory Allocation

Questions on Dynamic Memory Allocation : Question 1 :
The most appropriate matching for the following pairs (GATE CS 2000)
X: m=malloc(5); m= NULL;        1: using dangling pointers
Y: free(n); n->value=5;         2: using uninitialized pointers
Z: char *p; *p = ’a’;           3. lost memory is:

 X—1 Y—3 Z-2 (X—2 Y—1 Z-3 X—3 Y—2 Z-1 X—3 Y—1 Z-2  Correct
Questions on Dynamic Memory Allocation : Question 2 :
Consider the following three C functions :
[PI] int * g (void)
{
int x= 10;
return (&x);
}

[P2] int * g (void)
{
int * px;
*px= 10;
return px;
}

[P3] int *g (void)
{
int *px;
px = (int *) malloc (sizeof(int));
*px= 10;
return px;
}
Which of the above three functions are likely to cause problems with pointers? (GATE 2001)

 Only P3 Only P1 and P3 Only P1 and P2  Correct P1, P2 and P3
Questions on Dynamic Memory Allocation : Question 3 :
Output?
# include<stdio.h>
# include<stdlib.h>

void fun(int *a)
{
a = (int*)malloc(sizeof(int));
}

int main()
{
int *p;
fun(p);
*p = 6;
printf("%d\n",*p);
return(0);
}

 May not work  Correct Works and prints 6
Questions on Dynamic Memory Allocation : Question 4 :
Which of the following is/are true

 calloc() allocates the memory and also initializes the allocates memory to zero, while memory allocated using malloc() has random data. malloc() and memset() can be used to get the same effect as calloc(). calloc() takes two arguments, but malloc takes only 1 argument. Both malloc() and calloc() return 'void *' pointer. All of the above  Correct
Questions on Dynamic Memory Allocation : Question 5 :
What is the return type of malloc() or calloc()

 void *  Correct Pointer of allocated memory type void ** int *
Questions on Dynamic Memory Allocation : Question 6 :
Which of the following is true?

 "ptr = calloc(m, n)" is equivalent to following ptr = malloc(m * n); "ptr = calloc(m, n)" is equivalent to following ptr = malloc(m * n); memset(ptr, 0, m * n);  Correct "ptr = calloc(m, n)" is equivalent to following ptr = malloc(m); memset(ptr, 0, m); "ptr = calloc(m, n)" is equivalent to following ptr = malloc(n); memset(ptr, 0, n);
Questions on Dynamic Memory Allocation : Question 7 :
What is the problem with following code?
#include<stdio.h>
int main()
{
int *p = (int *)malloc(sizeof(int));

p = NULL;

free(p);
}

 Compiler Error: free can't be applied on NULL pointer Memory Leak  Correct Dangling Pointer The program may crash as free() is called for NULL pointer.
Questions on Dynamic Memory Allocation : Question 8 :
Consider the following program, where are i, j and k are stored in memory?
int i;
int main()
{
int j;
int *k = (int *) malloc (sizeof(int));
}

 i, j and k are stored in stack segment i and j are stored in stack segment. k is stored on heap. i is stored in BSS part of data segment, j is stored in stack segment. k is stored on heap.  Correct j is stored in BSS part of data segment, i is stored in stack segment. k is stored on heap.