ComputationalRadiationPhysics / student_project_python_bindings

The student project investigates the performance and memory handling of Python bindings for CUDA C++ code created with pybind11.
GNU General Public License v3.0
1 stars 0 forks source link

Using standard library container instead raw pointer #5

Closed SimeonEhrig closed 3 years ago

SimeonEhrig commented 3 years ago

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

Example: https://github.com/ComputationalRadiationPhysics/student_project_python_bindings/blob/a14c312e6792c4be5cbc12adce1509716e7eb832/my_phase-retrieval/phase_algo.hpp#L60

afif-ishamsyah commented 3 years ago

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?

SimeonEhrig commented 3 years ago

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);
afif-ishamsyah commented 3 years ago

yes, that's what I mean

SimeonEhrig commented 3 years ago

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.

SimeonEhrig commented 3 years ago

solved in 3dc70867695483fb9a2e4d3ca0c0ace0520c1ef6