What function is used to deallocate memory that was previously allocated by malloc?
Question
What function is used to deallocate memory that was previously allocated by malloc
?
Solution
The function used to deallocate memory that was previously allocated by malloc is free()
.
Here is a step by step guide on how to use it:
- First, you allocate memory using
malloc()
. For example:
int *ptr = (int*) malloc(sizeof(int));
This will allocate enough memory to store an integer and the pointer ptr
points to this memory.
- You can use the allocated memory to store an integer:
*ptr = 10;
- Once you are done with the memory (i.e., you don't need to use the stored integer anymore), you can deallocate the memory using
free()
. This is done as follows:
free(ptr);
After this step, the memory previously pointed to by ptr
is deallocated and can be used for other purposes.
- It's a good practice to set the pointer to
NULL
after freeing the memory to avoid dangling pointer:
ptr = NULL;
Remember, every malloc()
should have a corresponding free()
. If you forget to free the memory, it can lead to memory leaks where the memory is not available for other processes until your program ends.
Similar Questions
Which operator is used to allocate memory dynamically in C++?mallocallocnewcreate
The memory space reserved when calling malloc is on:The stackThe heapI don't know
blank is used to allocate memory to array variable in Javamalloc calloc new alloc
Which of the following correctly deallocates memory allocated for an array in C++?delete ptr;delete[] ptr;free(ptr);delete array ptr;
Select the correct answerWhich header file is required for dynamic memory allocation functions in C?Optionsstdio.hstdlib.hstring.hmalloc.h
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.