Knowee
Questions
Features
Study Tools

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?

🧐 Not the exact question you are looking for?Go ask a question

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:

  1. 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.

  1. You can use the allocated memory to store an integer:
*ptr = 10;
  1. 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.

  1. 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.

This problem has been solved

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:

1/3

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.