Search code examples
c++arraysrealloc

realloc pointer change when out of function


i am starting homework about dynamic array, first, I have a 2 dimensional array :

int initializeInfo[3][4] ={{77,68,0,0},{96,87,89,78},{70,90,86,0}};

and use pointer to store it:

int **ptr = (int**)malloc(3*sizeof(int));
int size = 0;
for(int i =0;i<3;i++){
    addInitiazeInfo(ptr,initializeInfo[i],size);
}

here is function addInitiazeInfo:

void addInitiazeInfo(int**& ptr, int arr[],int& size){
    ptr[size] = (int*)malloc(4*sizeof(int));
    if(ptr[size] == NULL){
        return;
    }
    ptr[size] = arr;
    size++;
}

It's run OK! The 2 dimensional array is store by ptr pointer.enter image description here

And I want to add new row, I think realloc is needed, then I try:

int arr[] = {3,4,5,6};
size++;            
ptr = (int**)realloc(ptr,size * sizeof( int ) );
ptr[size-1] = (int*)malloc(4*sizeof(int));
ptr[size-1] = arr;

But I think this is my trouble, the output make me hard to know how it happend: enter image description here

please help me, thanks everyone


Solution

  • When you do

    ptr[size] = arr;
    

    You are essentially assigning the address of arr, to ptr[size]. This means that the memory you just allocated is lost and successfully leaked.

    You want to manually copy element by element or use something like memcpy. It is likely this might fix your issue, depending on the rest of your code.