Question

I have the following code copied from internet and try to compile in the server with Tesla C2075 installed with should support double precision, I also compile the code with flag sm_20

#include <iostream>
#include <iomanip>
#include <fstream>
#include <cuda_runtime.h>
#include <cuComplex.h>
#include <cublas_v2.h>

using namespace std;

typedef double2 Complex;

#define m 1024
#define n 300
#define k 1024

int main(int argc, char *argv[])
{
  Complex _A[m*k], _B[k*n];
  Complex *A, *B;

  cudaMalloc((void**)&A, m*k*sizeof(Complex));
  cudaMalloc((void**)&B, k*n*sizeof(Complex));

  for (int i=0; i<m*k; i++) _A[i] = make_cuDoubleComplex(rand()/(double)RAND_MAX, rand()/(double)RAND_MAX);;
  for (int i=0; i<k*n; i++) _B[i] = make_cuDoubleComplex(rand()/(double)RAND_MAX, rand()/(double)RAND_MAX);

  cudaMemcpy( A, _A, (m*k)*sizeof(Complex), cudaMemcpyHostToDevice );
  cudaMemcpy( B, _B, (k*n)*sizeof(Complex), cudaMemcpyHostToDevice );

  return 0;
}

It does compile but in runtime, it always returns "Segmentation fault (core dumped)". Is that anything wrong with the code? Thanks.

Was it helpful?

Solution

Your arrays _A and _B are most likely too large to fit on the stack. A quick-n-dirty fix is to move the arrays out to global scope. A better fix is to allocate them dynamically using new and delete as follows:

Complex *_A = new Complex[m*k];
Complex *_B = new Complex[k*n];
...
delete [] _A;
delete [] _B;

An even better option, since you're using C++, is to use a std::vector:

std::vector < Complex > _A(m*k);
std::vector < Complex > _B(k*n);

// But now to get the pointer you need this:
cudaMemcpy( A, &_A[0], (m*k)*sizeof(Complex), cudaMemcpyHostToDevice );
// etc.

That &_A[0] syntax means: take the address of the first element of the vector, which is the same as a pointer to the entire array. The reason to prefer a vector over manually allocating the memory is that destruction/deallocation happens automatically when the variable goes out of scope, which is essential for writing exception-safe code.

You'll also need #include <vector>

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top