Resizing and Releasing Memory, Realloc,Free

When you no longer need a dynamically allocated memory block, you should give it back to the operating system. You can do this by calling the function free( ). Alternatively, you can increase or decrease the size of an allocated memory block by calling the function realloc( ). The prototypes of these functions are as follows:

void free( void * ptr ); 

The free( ) function releases the dynamically allocated memory block that begins at the address in ptr. A null pointer value for the ptr argument is permitted, and such a call has no effect.

void *realloc( void * ptr, size_t size ); 

The realloc( ) function releases the memory block addressed by ptr and allocates a new block of size bytes, returning its address. The new block may start at the same address as the old one.
realloc( ) also preserves the contents of the original memory blockup to the size of whichever block is smaller. If the new block doesn’t begin where the original one did, then realloc( ) copies the contents to the new memory block. If the new memory block is larger than the original, then the values of the additional bytes are unspecified.
It is permissible to pass a null pointer to realloc( ) as the argument ptr. If you do, then realloc( ) behaves similarly to malloc( ), and reserves a new memory block of the specified size.
The realloc( ) function returns a null pointer if it is unable to allocate a memory block of the size requested. In this case, it does not release the original memory block or alter its contents.


#include <stdio.h>
int main()
    char *a;
    // (typecast to data type)malloc(sizeof(data type));
    a = (char *)malloc(sizeof(char)*10);
    // size of a is 10
    a = "hello";
    // syntax : realloc(variable of size to be changed,new size)
    return 0;

You may also like...