0
0
Cprogramming~10 mins

realloc function - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to allocate memory for 10 integers using malloc.

C
#include <stdlib.h>

int *arr = (int *)[1](10 * sizeof(int));
Drag options to blanks, or click blank then click option'
Amalloc
Brealloc
Ccalloc
Dfree
Attempts:
3 left
💡 Hint
Common Mistakes
Using realloc before any memory is allocated.
Using free instead of malloc.
2fill in blank
medium

Complete the code to resize the memory block pointed by arr to hold 20 integers using realloc.

C
arr = (int *)[1](arr, 20 * sizeof(int));
Drag options to blanks, or click blank then click option'
Amalloc
Bcalloc
Crealloc
Dfree
Attempts:
3 left
💡 Hint
Common Mistakes
Using malloc instead of realloc to resize memory.
Not casting the return value of realloc.
3fill in blank
hard

Fix the error in the code to safely resize memory and check for allocation failure.

C
int *temp = (int *)[1](arr, 30 * sizeof(int));
if (temp == NULL) {
    // handle error
} else {
    arr = temp;
}
Drag options to blanks, or click blank then click option'
Arealloc
Bmalloc
Ccalloc
Dfree
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning realloc result directly to original pointer without checking for NULL.
Using free instead of realloc.
4fill in blank
hard

Fill both blanks to create a new array with double the size of the old one using realloc and initialize new elements to zero.

C
int old_size = 10;
int new_size = old_size * 2;
int *temp = (int *)[1](arr, new_size * sizeof(int));
if (temp != NULL) {
    for (int i = old_size; i < new_size; i++) {
        temp[i] = [2];
    }
    arr = temp;
}
Drag options to blanks, or click blank then click option'
Arealloc
Bmalloc
C0
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using malloc instead of realloc for resizing.
Initializing new elements with 1 instead of 0.
5fill in blank
hard

Fill all three blanks to safely resize an integer array, check for failure, and update the pointer.

C
int *temp = (int *)[1](arr, [2] * sizeof(int));
if (temp == [3]) {
    // handle allocation failure
} else {
    arr = temp;
}
Drag options to blanks, or click blank then click option'
Amalloc
Brealloc
C20
DNULL
Attempts:
3 left
💡 Hint
Common Mistakes
Using malloc instead of realloc for resizing.
Checking against 0 instead of NULL.
Not checking for allocation failure before updating pointer.