ComputationalRadiationPhysics / student_project_python_bindings

The student project investigates the performance and memory handling of Python bindings for CUDA C++ code created with pybind11.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using standard library container instead raw pointer

SimeonEhrig opened this issue · comments

Please use standard library container like std::vector instead raw pointer on the host side to avoid problems like memory leaks.

Example:

double *image_x = new double[dimension]; //initial image x, same size as magnitude

The image_x is not used anymore after the last commit. I forgot to delete it.

About using vector, for example :

double a = static_cast<double>(b);

is *a can be replaced by vector?

I'm a little bit confused about your code example, because at the moment, you cast an value with unknown type to a double value. Do you mean

int *b[10];

double *a = static_cast<double*>(b);

yes, that's what I mean

No, that's not possible. There are some reasons, but the main reason is, that std::vector has the ownership of his memory by definition. For example, if a cast would possible, the following example would cause, that the std::vector do an invalid memory access (segmentation fault) but that should be avoided by using std::vector:

int *b = new int[10];

// this is not valid, just for explanation
double *a = static_cast<double*>(b);
delete[] b;
// segmentation fault
std::cout << a[0] << std::endl;

A conversion from a C array to std::vector is only possible with a memory copy.

int *input[10];

// create a vector and copy each element of input
vector<int> vec_int(input, input + 10);

// with a cast, it becomes a little bit more difficult

// create a vector with the same size like the c array
std::vector<double> vec_double(10);
// take each element of the c array, apply a type cast on it and write it to the vector
std::transform(input, input + 10, vec_double.begin(), [](int in){return static_cast<double>(in);});

From the performance view, if you get your data as pointer, it makes more sense to use the pointer, instead converting it in a c++ vector.

solved in 3dc7086