Search code examples
c++arraysmemset

c++ memset cause segment fault of int** pointer


    int **dpTable = new int* [iMatrixHeight + 1];
    for (int i = 0; i < iMatrixHeight + 1; i++)
    {
        dpTable[i] = new int [iMatrixWidth + 1];
    }

    memset(dpTable, 0, (sizeof(int)) * (iMatrixHeight + 1)*(iMatrixWidth + 1));

I'm using operator new to allocate a two-dimensional array, but if I use memset to initialize the array, I got a segmentfault when I access the array later. Without the memset, it's ok.

Am I doing anything wrong? THX!


Solution

  • The arrays dpTable[i] do not point to contiguous memory. You have to initialize then one by one

    for (int i = 0; i < iMatrixHeight + 1; i++)
    {
        dpTable[i] = new int [iMatrixWidth + 1];
        memset(dpTable[i], 0, (iMatrixWidth + 1) * sizeof(int)) ;
    }