realloc in c
Answer:
The realloc
function in C is used to dynamically resize the memory allocated for a previously allocated block. It takes two arguments: a pointer to the previously allocated memory block and the new size that the block should be resized to. The function returns a pointer to the resized memory block.
Here is the syntax for realloc
:
void realloc(void ptr, size_t size);
The ptr
argument is a pointer to the memory block that needs to be resized. If ptr
is a null pointer, then realloc
behaves like malloc
and allocates a new memory block of the given size.
The size
argument specifies the new size for the memory block. If size
is 0, then realloc
behaves like free
and deallocates the memory block pointed to by ptr
.
When realloc
is called, it performs the following actions:
- If
ptr
is a null pointer, it behaves likemalloc
and allocates a new memory block of sizesize
. - If
ptr
is not a null pointer, it tries to resize the memory block pointed to byptr
to the new sizesize
. - If the new size is smaller than the current size, the extra bytes are deallocated.
- If the new size is larger than the current size,
realloc
tries to extend the memory block. If there is sufficient adjacent free space, it extends the block in-place. Otherwise, it allocates a new block of the requested size, copies the contents of the old block to the new block, and frees the old block. - If the new size is equal to the current size,
realloc
does nothing and returns the original pointerptr
. - If
realloc
is successful in resizing the memory block, it returns a pointer to the resized memory block. If it fails to resize the block, it returns a null pointer.
It's important to note that the original contents of the memory block may be preserved during resizing, but this is not guaranteed. Therefore, it's good practice to assign the returned pointer to the original pointer variable to avoid potential memory leaks.
Here's an example usage of realloc
:
#include <stdio.h>
#include <stdlib.h>
int main() {
int ptr = (int )malloc(5 * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Use the memory block...
ptr = (int )realloc(ptr, 10 sizeof(int));
if (ptr == NULL) {
printf("Memory reallocation failed.\n");
return 1;
}
// Use the resized memory block...
free(ptr);
return 0;
}
In this example, we initially allocate a memory block of size 5 sizeof(int)
using malloc
. Then, we use the memory block for some purpose. Later, we resize the memory block to a new size of 10 sizeof(int)
using realloc
. Finally, we free the memory block using free
.