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
NULLafter 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
What does malloc function do in C?
Which operator is used to allocate memory dynamically in C++?mallocallocnewcreate
What does malloc function do in C?Marks : 1Negative Marks : 0Answer hereAllocates memory and initializes it to zeroAllocates memory without initializing itFrees allocated memoryReallocates memory
What is malloc
The memory space reserved when calling malloc is on:
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.