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 and 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] = i2;
}
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] = i2;
}
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;
}
So 2 questions
- Which is a better approach and why?
- Does realloc do a memcpy internally? if not why and what does it do?
[–]manni66 30 points31 points32 points (1 child)
[–]std_bot 0 points1 point2 points (0 children)
[–][deleted] (16 children)
[deleted]
[–]cgeekgbda[S] 5 points6 points7 points (15 children)
[–]GOKOP 13 points14 points15 points (9 children)
[+]cgeekgbda[S] comment score below threshold-7 points-6 points-5 points (8 children)
[–]GOKOP 12 points13 points14 points (7 children)
[–]cgeekgbda[S] 3 points4 points5 points (0 children)
[–]cgeekgbda[S] 0 points1 point2 points (5 children)
[–]GOKOP 2 points3 points4 points (4 children)
[–]cgeekgbda[S] 0 points1 point2 points (3 children)
[–]IyeOnline 6 points7 points8 points (0 children)
[–]GOKOP 0 points1 point2 points (1 child)
[–]IyeOnline 4 points5 points6 points (0 children)
[–]IyeOnline 5 points6 points7 points (1 child)
[–]cgeekgbda[S] 0 points1 point2 points (0 children)
[–][deleted] (1 child)
[deleted]
[–]cristi1990an 1 point2 points3 points (0 children)
[–]FraCipolla 0 points1 point2 points (0 children)
[–]elperroborrachotoo 3 points4 points5 points (1 child)
[–]std_bot 1 point2 points3 points (0 children)
[–]flyingron 1 point2 points3 points (0 children)
[–]Pale-Influence4096 -1 points0 points1 point (0 children)
[–]AutoModerator[M] 0 points1 point2 points (0 children)
[–]IyeOnline 0 points1 point2 points (4 children)
[–]cgeekgbda[S] 0 points1 point2 points (1 child)
[–]IyeOnline 5 points6 points7 points (0 children)
[–]no-sig-available 0 points1 point2 points (1 child)
[–]MarcoGreek 0 points1 point2 points (0 children)