SoFunction
Updated on 2025-03-02

Dynamic allocation of C language memory comparison between malloc and realloc

C—Different between malloc and realloc in dynamic memory allocation

When memory is allocated during execution of a program, this space in the memory area is called a heap. There is another memory area called stack where space is allocated to the function's parameters and local variables. After executing the function, the memory space for storing parameters and local variables is freed. The memory in the heap is controlled by the programmer. When allocating memory on the heap, the programmer keeps track of when the allocated memory is no longer needed and frees up this space to facilitate reuse of them later.

The obvious advantage of using dynamic memory is that there is no need to pre-allocate storage space and the allocated space can be expanded or reduced according to the needs of the program, so that memory space can be used effectively.

malloc and free

malloc and free in the C function library are used to perform dynamic memory allocation and release respectively. The prototypes of these two functions are shown below, and they are both declared in the header file.

     void *malloc ( size_t size );

     void free ( void *pointer );

The function of malloc is to allocate a continuous space of length of size in the dynamic memory area of ​​memory. Its parameter is an unsigned shaping number, and the return value is a pointer to the starting address of the assigned continuous storage domain. Another thing that must be noted is that when the function fails to allocate storage space successfully (such as insufficient memory), a NULL pointer will be returned. Therefore, when calling this function, you should check whether the return value is NULL, and it is very important to ensure that it is not empty before use. The memory allocated by malloc is a continuous piece of space. At the same time, malloc may actually allocate a little more memory space than you request, but this behavior is only defined by the compiler. malloc does not know the data type that the memory requested by the user needs to store, so malloc returns a void * pointer, which can be converted into any other type of pointer.

Since the memory area is always limited, it cannot be allocated without limitation, and a program needs to save resources as much as possible, when the allocated memory area is not used, it must be released for other variables or programs to use. At this time, we need to use the free function. The free parameter must either be NULL or the value returned from malloc, relloc, calloc. The function is to free the memory space pointed to by the previously returned pointer, and passing a NULL parameter to free will not have any effect.

Differences between calloc and realloc and malloc

The prototypes of calloc and realloc are as follows:

     void *calloc ( size_t num_elements, size_t element_size );

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

The main difference between calloc and malloc is that the former initializes it to 0 before returning a pointer to memory, and in addition, they request differently. The calloc parameter includes the number of elements required and the bytes of each element. Based on these values, the total memory space to be allocated can be calculated.

The realloc function is used to modify the size of a memory block that has been allocated, which can expand or shrink a piece of memory. When the address of the starting space is empty, that is, *ptr = NULL, the same as malloc. When *ptr is not empty: if nuw_size < size, it means reducing the memory space pointed to by *ptr, part of the memory at the end of the memory block is removed, and the original content of the remaining memory remains; if nuw_size > size, it means expanding the memory space pointed to by *ptr. If the original memory tail has enough space to expand, memory will be added directly at the end of the original memory block. If the original memory tail space is insufficient, or the original memory block cannot change the size, realloc will re-alloc will re-alloc will also re-alloc will copy the content of the original memory block to the new memory block. Therefore, after using realloc, you should use the new pointer returned by realloc instead.

Example of usage program

int *ptr =NULL;
ptr = (int*)malloc(sizeof(int)*size);
if (*ptr == NULL)
{
    strerror(error);
    return;
}

In the above example, size integer storage areas are dynamically allocated. The steps of dynamically allocating memory can be subdivided into: allocating continuous storage space of size integers, and returning an integer pointer to its starting address assigning this integer pointer address to ptr, detecting whether the return value is NULL. Note that type conversion (int*) converts the address returned by the function into a pointer of type int. This is done because malloc() is a general purpose function that allocates memory for any type of data. sizeof is an operator that returns an unsigned integer of type size_t, which is the number of bytes required to store its parameters. It takes keywords such as int or float as parameters and returns the number of bytes required to store data items of that type. Its parameters can also be variable or array names. When the array name is used as a parameter, sizeof returns the number of bytes required to store the entire array. The previous example requests allocating memory enough to store sizes int data items. Using sizeof in this way can automatically adjust the required memory space according to the value of the int type by different C compilers.

int *p1,*p2; 
p1 = (int*)malloc(size * sizeof(int));
p2=p1; 
……  
free(p1);  /* or free(p2)*/

Passing other values ​​to the free function may cause crashes or other catastrophic consequences. Note: What is important here is the value of the pointer, not the pointer itself used to apply for dynamic memory.

The return value of malloc is assigned to p1, and the value of p1 is assigned to p2, so at this time p1 and p2 can be used as parameters of the free function. The malloc function is to allocate the storage area. The free function releases memory areas that are no longer used. Therefore, these two functions can dynamically allocate and simple management of memory areas.

Here are the basic rules for using dynamically allocated memory:

  • Avoid allocating large amounts of small memory blocks. There is some system overhead for allocating memory on the heap, so allocating many small memory blocks is greater than allocating several large memory blocks.
  • Allocate memory only when needed. As long as the memory block on the heap is used, it is released.
  • Always make sure to free allocated memory. When writing code that allocates memory, you must determine where to free memory in the code.
  • Before freeing memory, make sure that the address of the allocated memory on the heap is not accidentally overwritten, otherwise the program will experience a memory leak. Be especially careful when allocating memory in a loop.

This is the article about the dynamic allocation of C memory comparison between malloc and realloc. For more related C language comparisons, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!