Home > OS >  most likely I am allocating memory incorrectly somewhere
most likely I am allocating memory incorrectly somewhere

Time:12-28

please help me. I have a function. it should delete the row under the index number. I'm creating a new two-dimensional array. I allocate memory for it. I clear the memory from the source array and allocate it for it again.

int **matrix;

it is my matrix

int** delete_with_index(int n,int m, int **arr, int index){
    int i, g;
    int **new_arr;
    new_arr= malloc(n*sizeof(int *));
    for (i=0;i<n;i  ){
        new_arr[i]=malloc(m*sizeof(int));
    }
    for (i=0;i<n;i  ){
        for (g=0;g<m;g  ){
            new_arr[i][g]=arr[i][g];
        }
        free(arr[i]);
    }
    free(arr);
    arr= malloc((n-1)*sizeof(int *));
    for (i=0;i<(n-1);i  ){
        arr[i]=malloc(m*sizeof(int));
    }
    for (i=0;i<index;i  ){
        for (g=0;g<m;g  ){
            arr[i][g]=new_arr[i][g];
        }
        free(new_arr[i]);
    }
    for (i=index 1;i<n;i  ){
        for (g=0;g<m;g  ){
            arr[i][g]=new_arr[i-1][g];
        }
        free(new_arr[i-1]);
    }
    free(new_arr);
    return arr;
}

it is my func

res_m = delete_with_index(n1, m1, res_m, index);

it is how i call it

CodePudding user response:

  1. It is not 2D array only array of pointers. You do not have to copy all the elements, only the pointers. You do not have to pass size of allocated memory for every row as it is not needed.
  2. Use correct types for sizes
  3. You do not need a new array but this function will allocate and return one if createnew parameter is true.
int **deleteROW(const size_t rows, int **arr, size_t index, int createnew, int freeDeleted)
{
    int **newArray = NULL;

    if(arr && rows)
    {
        if(createnew)
        {
            newArray = malloc(sizeof(*newArray) * (rows - 1));
        }
        else
        {
            newArray = arr;
        }
        if(newArray)
        {
             if(freeDeleted) free(arr[index];
             memmove(newArray, arr, index * sizeof(*newArray));
             memmove(newArray   index, arr   index   1, (rows - index - 1) * sizeof(newArray));
        }  
    }
    return newArray;
}

If you simply want to delete a row from the array of pointers:

int **deleteROW(const size_t rows, int **arr, size_t index, int freeDeleted)
{
    int **newArray = NULL;

    if(arr && rows)
    {
        if(freeDeleted) free(arr[index])
        memmove(&arr[index], &arr[index   1], (rows - index - 1) * sizeof(*newArray));
    }
    return arr;
}

If you want to delete a row from a real 2D array you simply need to:

void *deleteROW(const size_t rows, size_t cols, int (*arr)[cols], size_t index)
{
    if(arr && rows && cols && index < rows - 1)
    {
        memmove(arr[index], arr[index   1], (rows - index - 1) * sizeof(*arr));
    }
    return arr;
}
  • Related