It is good practice to check CUDA API errors when calling cudaMalloc() and other functions. It also helps to find floating bugs caused by hardware (lack of memory, etc.). Below I provide an adapted version of CudaSafeCall that I found many weeks ago on the Internet. Simply remove #define CUDA_ERROR_CHECK in production if it is unneeded.
1#include <iostream>
2#include <cuda.h>
3
4#define CUDA_ERROR_CHECK
5
6#define CudaSafeCall(error) __cudaSafeCall(error, __FILE__, __LINE__)
7
8inline void __cudaSafeCall(cudaError error, const char *file, const int line)
9{
10#ifdef CUDA_ERROR_CHECK
11 if (error != cudaSuccess ) {
12 std::cout << "error: CudaSafeCall() failed at " << file
13 << ":" << line
14 << " with \"" << cudaGetErrorString(error) << "\""
15 << std::endl;
16 exit( -1 );
17 }
18#endif
19}
20
21int main(int argc, char **argv)
22{
23 float *d_array;
24 size_t N = 1024;
25 CudaSafeCall(cudaMalloc((void **)&d_array, N*N*N*N));
26 CudaSafeCall(cudaFree(d_array));
27 return 0;
28}