Is there any way to free some part of memory you created by using malloc();
suppose:-
int *temp;
temp = ( int *) malloc ( 10 * sizeof(int));
free(temp);
free() will release all 20 byte of memory but suppose i only need 10 bytes. Can i free last 10 bytes.
The memory for variables is automatically deallocated at compile time. In dynamic memory allocation, you have to deallocate memory explicitly. If not done, you may encounter out of memory error. The free() function is called to release/deallocate memory in C.
C malloc() methodThe “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form.
Dynamic allocations with new/delete are said to take place on the free-store, while malloc/free operations use the heap.
This is known as dynamic memory allocation in C programming. To allocate memory dynamically, library functions are malloc() , calloc() , realloc() and free() are used. These functions are defined in the <stdlib. h> header file.
You should use the standard library function realloc
. As the name suggests, it reallocates a block of memory. Its prototype is (contained in the header stdlib.h
)
void *realloc(void *ptr, size_t size);
The function changes the size of the memory block pointed to by ptr
to size
bytes. This memory block must have been allocated by a malloc
, realloc
or calloc
call. It is important to note that realloc
may extend the older block to size
bytes, may keep the same block and free the extra bytes, or may allocate an entirely new block of memory, copy the content from the older block to the newer block, and then free
the older block.
realloc
returns a pointer to the block of reallocated memory. If it fails to reallocate memory, then it returns NULL and the original block of memory is left untouched. Therefore, you should store the value of ptr
in a temp variable before calling realloc
else original memory block will be lost and cause memory leak. Also, you should not cast the result of malloc
- Do I cast the result of malloc?
// allocate memory for 10 integers
int *arr = malloc(10 * sizeof *arr);
// check arr for NULL in case malloc fails
// save the value of arr in temp in case
// realloc fails
int *temp = arr;
// realloc may keep the same block of memory
// and free the memory for the extra 5 elements
// or may allocate a new block for 5 elements,
// copy the first five elements from the older block to the
// newer block and then free the older block
arr = realloc(arr, 5 * sizeof *arr);
if(arr == NULL) {
// realloc failed
arr = temp;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With