Challenge your understanding of dynamic memory allocation in C with this quiz focused on malloc, calloc, and free. Strengthen your grasp of syntax, error prevention, and best practices for safe and effective memory management in C programming.
What is a key difference between malloc and calloc when allocating memory for an array of 10 integers?
Explanation: The correct answer is that malloc does not initialize memory, whereas calloc initializes every byte of allocated memory to zero, which helps prevent the use of garbage values. Option two is incorrect since neither function sets memory to one. The third option is wrong; calloc requires both the number of elements and the size of each element. The last option is false because both malloc and calloc allocate memory only on the heap, not the stack.
Which statement best describes how to properly release memory allocated using malloc or calloc?
Explanation: You must use the free function and pass it the pointer previously returned by malloc or calloc to release the allocated memory. Setting a pointer to NULL does not free memory; it just detaches the reference, causing a memory leak. Using realloc with zero size can free memory for some implementations, but free is the standard and clear approach. Memory allocated with malloc is not freed automatically on program termination in all cases, especially with long-running or embedded systems.
In the following C snippet, which best describes the memory management issue?nnint *arr = malloc(100 * sizeof(int)); /* ...some code... */ arr = malloc(50 * sizeof(int));
Explanation: Overwriting the pointer arr with a new malloc result without freeing the previously allocated memory leads to a memory leak. There is no double free as free is never called in the snippet. The memory is not properly managed, so option three is incorrect. The usage of malloc for allocating integers is correct, so option four is invalid.
Which is the correct way to allocate memory for an array of 20 floats using calloc in C?
Explanation: The correct calloc usage is to provide the number of elements (20) and the size of each (sizeof(float)), as in the first option. The second option has the arguments reversed, which may lead to errors or incorrect memory allocation. The third option with malloc only allocates 20 bytes, not enough for 20 floats on most systems. The last option is an incorrect function signature for malloc, which only takes one argument.
What happens if you call free on a pointer that has already been set to NULL in a C program?
Explanation: Calling free on a NULL pointer is defined as a safe no-operation; the function simply does nothing. There is no segmentation fault or program crash in this scenario, so option two is false. The pointer itself remains NULL after the call and no uninitialized state occurs, making option three incorrect. Freeing memory at NULL is not an action since NULL does not refer to allocated memory, so option four is also inaccurate.