Search code examples
carraysresizemallocfree

Segmentation fault during resizing two-dimensional dynamically allocated table


I`ve got two-dimensional, dynamically allocated table. Resize the table.

1) Create new one.

2) Delete previous pointer, allocated memory.

3) Assign new pointer.

Code:

#include <stdio.h>
#include <stdlib.h>

int** create(int rows, int columns)
{
    int **tab = (int**)malloc(rows * sizeof(int*));
    int i=0;
    for(;i<rows; ++i)
    {
        tab[i] = (int*)malloc(columns * sizeof(int));   /* tab[i] = (int*)calloc(columns , sizeof(int)); */
    }

    return tab;
}
void deleteTab(int **tab, int rows)
{
    int i=0;
    for(;i<rows;++i)
    {
        free(tab[i]);
    }
    free(tab);
}
void resize(int **tab, int oldRows, int newRows, int newColumns)
{
    int **newTab=create(newRows, newColumns);
    deleteTab(tab, oldRows);
    tab=newTab;
}
void printTab(int **tab, int rows, int columns)
{
    int i=0, j=0;
    for(i=0;i<rows;++i, printf("\n"))
    {
        for(j=0;j<columns;++j)
        {
            printf("%i ", tab[i][j]);
        }
    }
}
int main()
{
    int **tab=create(4,7);
    resize(tab,4,8,9);
    int i=0, j=0;
    for(i=0;i<8;++i)
    {
        for(j=0;j<9;++j)
        {
            tab[i][j]=3;
        }
    }
    printTab(tab,8,9);
}

Output: Segmentation fault.

Is it a good way/algorithm to resize the table? How to omit segmentation fault error?


Solution

  • resize must return newtab. the parameter is passed by value. or you can make tab as a pointer of your table and change your code like this

    void resize(int ***tab, int oldRows, int newRows, int newColumns)
    {
        int **newTab=create(newRows, newColumns);
        deleteTab(*tab, oldRows);
        *tab=newTab;
    }
    

    and call it like this:

    int main()
    {
        int **tab=create(4,7);
        resize(&tab,4,8,9); //note 'tab' now pass-by-pointer
        //...
    }