Search code examples
c++memset

Access violation writing error on writing to a 2D array after initializing using memset


I am using Visual Studio Community 2017.

Following the discussion below:

Fastest way to zero out a 2d array in C?

I have a 2 D matrix (10 x 10) that I initialize using memset. This is option 1.

Option 2 is initializing the same matrix using two for loops, each looping from 0 through 9.

Then, when I write to a valid matrix location, an access violation writing error is thrown when Option 1 was used. Everything works fine when Option 2 is used.

The minimal working code I have that replicates this is given below:

#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
#include <math.h>
#include <cmath>
#include <vector>
#include <string>
#include <limits.h>
#include <stdlib.h>
#include <array> 



int main(){
    double ** cmatrix = new double*[10];
    for (int i = 0; i < 10; i++)
        cmatrix[i] = new double[10];

    memset(cmatrix, 0, 10 * 10 * sizeof(double));//Option 1    

    //for (int i = 0; i < 10; i++)//Option 2
        //for (int j = 0; j < 10; j++)
            //cmatrix[i][j] = 0;

    cmatrix[0][1] = 5;//This step produces error on Option 1, but not on option 2

    return 0;
}

Any help is appreciated.


Solution

  • With the memset you're overriding the pointers returned by your memory allocations, therefore when you access the memory later you're actually deferring a null pointer.

    Your 2D array is actually an array of pointers, so memory is not contiguous and you cannot do a memset to set it to 0. Technically, it is just a pointer and dynamically you allocate space for another 10 pointers, each of them pointing to 10 doubles.

    Instead, use a double loop (nested-fors) to initialize it, or just one memset for each row:

    for (int i = 0; i < 10; ++i)
      for (int j = 0; j < 10; ++j)
        cmatrix[i][j] = 0.0;
    
    // or
    
    for (int i = 0; i < 10; ++i)
      memset(cmatrix[i], 0, 10 * sizeof(double));
    

    Also, if your array will always be 10x10 you can declare it instead as double cmatrix[10][10]: that memory is contiguous and you can do your original memset.