0
    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!

4
  • 2
    you're trying to fill an array of pointers with an array of integers, and you're overshooting by a factor of (iMatrixWidth + 1) (+/- the difference between pointer size and int). Commented Jun 5, 2015 at 14:57
  • 2
    You're using memset to obliterate the entire sequence of pointers your for-loop just worked so hard to acquire. (and breaching the sequence in the process just to add salt to the wound). Commented Jun 5, 2015 at 14:58
  • Another question I'd ask is what's the intended purpose for the +1. Why not just set iMetrixHeight accordingly? Commented Jun 5, 2015 at 15:00
  • possible duplicate of Initialize a double pointer with zeros in C++ Commented Jun 5, 2015 at 15:12

2 Answers 2

5

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)) ;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Simply dpTable[i] = new int [iMatrixWidth + 1](); will work as well, if the OP has anything closely resembling a modern C++ compiler. No memset required in that case.
Oh yes, it suddenly struck me
2

Instead of this code:

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));

… you can do this:

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

Look ma, no memset – instead asking for zeroing of the memory.

Still that's very ugly in C++.

So, do this:

vector<vector<int>> table( iMatrixHeight + 1, vector<int>( iMatrixWidth + 1 ) );

where vector is std::vector.

Or, consider defining a matrix class with just a single vector as backing store.

Or just use an existing matrix class, e.g. from Boost.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.