0

A is a 2d array and data is 1d array

double **A, *data;

fullsize is 9222, memory allocation:

A = (double **)malloc((fullsize)*sizeof(double *));         //allocate memory dynamically for matrix A
for (i = 0; i < fullsize; i++)
    A[i] = (double *)malloc((2 * fullsize)*sizeof(double));

data = (double *)malloc((fullsize*fullsize)*sizeof(double *));

conversion logic:

{
    for (int n = 0; n<fullsize; n++)
    for (int m = 0; m<fullsize; m++)
    {
        data[n*fullsize + m] = A[n][m];
    }
}

error log:

The thread 0xad80 has exited with code 0 (0x0).
Unhandled exception at 0x00F5E6E9 in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0x69E65000.

The program '[50964] ConsoleApplication1.exe' has exited with code 0 (0x0).
Sanju
  • 115
  • 1
  • 13

1 Answers1

1

You are allocating data using size of double pointer:

data = (double *)malloc((fullsize*fullsize)*sizeof(double *));
//                                                        ^

It should be allocated using sizeof(double) instead.

You can avoid using malloc in C++ by using vectors. If you want exact sizes on allocations, use new double[...] instead. In either case you will end up with more readable code:

double **A = new double*[fullsize];
for (int i = 0 ; i != fullsize ; i++) {
    A[i] = new double[fullsize];
}
double *data = new double[fullsize*fullsize];
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I tried `sizeof(double)` its still giving the same error, I need arrays for conversion into Eigen matrix; – Sanju Aug 02 '17 at 11:39
  • @Sanju Did you try `new`? Also, `2` in `malloc((2 * fullsize)*sizeof(double))` looks suspicious. Is your matrix not square? – Sergey Kalinichenko Aug 02 '17 at 12:06
  • 1
    Is any of the malloc failing (returning 0)? – Paolo Brandoli Aug 02 '17 at 12:06
  • It seems that your malloc returns nullptr somewhere. Also @dasblinkenlight is right you don't need the 2*fullsize. Try compiling your application using clang with: `-fsanitize=address -fno-omit-frame-pointer -O1 -g` Plus you can do this trick if you want to: `double* data = ( double* ) malloc( fullsize * fullsize * sizeof( double ) ); double** A = static_cast< double** >( &data );` This way you will have both views onto one continuous memory block. – olgierdh Aug 02 '17 at 15:24