© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

17. What is the difference between "calloc(...)" and "malloc(...)"?

Ans:
1. calloc(...) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0. The total number of memory allocated will be (number_of_elements * size).

malloc(...) takes in only a single argument which is the memory required in bytes. malloc(...) allocated bytes of memory and not blocks of memory like calloc(...).

2. malloc(...) allocates memory blocks and returns a void pointer to the allocated space, or NULL if there is insufficient memory available.

calloc(...) allocates an array in memory with elements initialized to 0 and returns a pointer to the allocated space. calloc(...) calls malloc(...) in order to use the C++ _set_new_mode function to set the new handler mode.

Ex - 1: What will be the result of the following program ?
int aaa() {printf(“Hi”);}
int bbb(){printf(“hello”);}
iny ccc(){printf(“bye”);} 
main()
{
int ( * ptr[3]) ();
ptr[0] = aaa;
ptr[1] = bbb;
ptr[2] =ccc;
ptr[2]();
}
Ans:
 bye
Explanation:

int (* ptr[3])() says that ptr is an array of pointers to functions that takes no arguments and returns the type int. By the assignment ptr[0] = aaa; it means that the first function pointer in the array is initialized with the address of the function aaa. Similarly, the other two array elements also get initialized with the addresses of the functions bbb and ccc. Since ptr[2] contains the address of the function ccc, the call to the function ptr[2]() is same as calling ccc(). So it results in printing  "bye".

Ex - 2: Find the output for the following C program
#include<stdio.h>
               void func(int *x)
                 {
                     x=(int *) malloc(sizeof(int));
                     printf("in func: %p\n",x);
                }
                   void main(int argc)
             {
              int **pp;
              int *p;
              pp=(int **) malloc(sizeof(int *));
              p=(int *) malloc(sizeof((int));
              *pp=p;
              printf("first:%p \n",*pp);
              func(*pp);
             printf("last %p \n",*pp);
             }
assuming the p is equal to 1000 and x is equal to 2000 after malloc calls
a) 1000,2000,1000,
b) 1000,2000,2000,
c) 1000,1000,1000,
d) 2000,2000,2000
Ans: a


SLogix Student Projects
bottom