Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to allocate memory for an integer pointer.
C
int *ptr = (int *)[1](sizeof(int)); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using free instead of malloc causes errors because free releases memory.
Using sizeof alone does not allocate memory.
✗ Incorrect
The malloc function allocates memory dynamically. Here, it allocates enough space for one integer.
2fill in blank
mediumComplete the code to release the allocated memory.
C
free([1]); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing sizeof or malloc to free causes runtime errors.
Passing NULL to free does nothing but is not useful here.
✗ Incorrect
The free function releases the memory pointed to by ptr.
3fill in blank
hardFix the error in the code to allocate memory for 5 integers.
C
int *arr = (int *)malloc([1] * sizeof(int)); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using sizeof(arr) gives size of pointer, not the number of elements.
Using 0 allocates no memory.
✗ Incorrect
To allocate memory for 5 integers, multiply 5 by the size of an integer.
4fill in blank
hardFill both blanks to create a loop that initializes the allocated array to zero.
C
for (int [1] = 0; [2] < 5; [1]++) { arr[[1]] = 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in the loop causes errors.
Using a variable not declared causes compilation errors.
✗ Incorrect
The variable i is used as the loop counter consistently in all parts of the for loop.
5fill in blank
hardFill all three blanks to safely allocate memory and check if allocation succeeded.
C
int *ptr = (int *)[1](sizeof(int) * [2]); if ([3] == NULL) { printf("Memory allocation failed\n"); return 1; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using free instead of malloc causes errors.
Not checking if pointer is NULL can cause crashes.
Using wrong variable name in the if condition causes errors.
✗ Incorrect
Use malloc to allocate memory for 10 integers. Then check if ptr is NULL to detect failure.