Which function allocates memory for an array by taking the number of elements…

2019

Which function allocates memory for an array by taking the number of elements and the size of each element?

Answer: D. calloc( )ConceptDynamic memory allocation obtains storage at run time from the heap. In ISO C, malloc requests one uninitialized block, while calloc requests storage…

  1. A.

    malloc( )

  2. B.

    realloc( )

  3. C.

    alloc( )

  4. D.

    calloc( )

Attempted by 2 students.

Show answer & explanation

Correct answer: D

Concept

Dynamic memory allocation obtains storage at run time from the heap. In ISO C, malloc requests one uninitialized block, while calloc requests storage for a specified number of equal-sized elements.

The storage returned by calloc is additionally zero-initialized byte by byte. This count-and-size interface makes its array-allocation role explicit.

Application

The stem asks for the function whose interface accepts the element count and the size of each element separately. In calloc(count, size), count is the number of elements and size is the size of each element.

For example, calloc(10, sizeof(int)) reserves contiguous storage for 10 int elements and initializes every byte of that storage to zero.

Contrast

  • malloc(size) allocates a single uninitialized block; the caller must calculate the total array size.

  • realloc(ptr, new_size) resizes storage that was allocated earlier.

  • alloc() is not an ISO C allocation function from <stdlib.h>.

  • calloc(count, size) combines an element count with an element size and zero-initializes the allocated bytes.

Result

Therefore, the function described is calloc().

Explore the full course: Uppsc Computer Operator Grade B

Loading lesson…