What could be the best approach to reallocate the memory of dynamically allocated arrays? [closed]

  softwareengineering

What could be the best approach to rellocate memory for dynamically allocated array?

Say with the help of malloc we initially allocated 10 integer size memory. Now we want to change it to point to 20 size of integers array.

What is the difference and the best way to achieve the same? Using realloc or using calloc+memcpy?

Does by any chance realloc does a memcopy?

Using realloc:

#include <iostream>
#include <cstring>

int main()
{
    int *array1 = (int *) malloc(10 * sizeof(int));
    for(size_t i = 0; i < 10; i++)
    {
        array1[i] = i*2;
    }
    
    for(size_t i = 0; i < 10; i++)
    {
        std::cout<<array1[i] <<" ";
    }
    
    std::cout<<std::endl;
    
    int *array2 = (int *)realloc(array1, 20 * sizeof(int));
        
    for(size_t i = 0; i < 20; i++)
    {
        std::cout<<array2[i] <<" ";
    }
    

    return 0;
}

and using calloc+memcpy

#include <iostream>
#include <cstring>

int main()
{
    int *array1 = (int *) malloc(10 * sizeof(int));
    for(size_t i = 0; i < 10; i++)
    {
        array1[i] = i*2;
    }
    
    for(size_t i = 0; i < 10; i++)
    {
        std::cout<<array1[i] <<" ";
    }
    
    std::cout<<std::endl;
        
    int *array2 = (int *) calloc(20, sizeof(int));
    memcpy(array2, array1, sizeof(int)*10);
    
    for(size_t i = 0; i < 20; i++)
    {
        std::cout<<array2[i] <<" ";
    }
    

    return 0;
}

Which is a better approach and why? Does realloc do a memcpy internally?

7

C++ is not C. The best way to manage arrays of dynamic size is to not reinvent the wheel and use std::vector. It was optimized for a number of situation your code doesn’t deal with, but in addition, it’s safe.

The correct way to create dynamically object is to use new. malloc() and calloc() are very tricky to use in C++ because they do not support correctly the object lifecycle. It works for very simple types like int and char, but quickly goes into undefined behavior with more complex types, if you do not use it in combination with placement new to create objects at precise memory addresses.

Using memcpy() in C++ should be avoided at all cost. Again, this function doesn’t cope with object lifecycle. It works only for trivially copiable types and even then, only if you do not break the lifecycle of objects that may exist at target address. The right way to copy a container is to to use std::copy().

1

LEAVE A COMMENT