Object Destructor Not Working

I wrote an object and destructor for said object that allocates an array on global memory. The problem is my deletion isn’t happening, which I can see because cudaMemGetInfo is saying I have the same amount of free memory before and after I call delete on the object. Here is what the code looks like. Can anyone spot what I could be doing wrong?

class myClass{

      int* ptr2myDeviceArray;


      myClass(int size);



myClass::myClass(int size){

    ptr2myDeviceArray = cudaMalloc( (void**)&ptr2myDeviceArray, size);



    cudaFree( (void**)&ptr2myDeviceArray );


int main(){

    myClass* ptr2myClass = new myClass();

size_t freeMemBefore;

    size_t totalMemBefore;

    cudaMemGetInfo(&freeMemBefore, &totalMemBefore);

    std::cout << freeMemBefore << std::endl;

delete ptr2myClass;

size_t freeMemAfter;

    size_t totalMemAfter;

    cudaMemGetInfo(&freeMemAfter, &totalMemAfter);

    std::cout << freeMemAfter << std::endl;

return 0;


Freemem before and after prints out the exact same value.

You’re misusing cudaMalloc and cudaFree. Their signature is:

cudaError_t cudaMalloc (void ∗∗ devPtr, size_t size)

cudaError_t cudaFree (void ∗ devPtr)
  1. You shouldn’t set the pointer with cudaMalloc’s return value. It’s set inside cudaMalloc by the pointer you pass. The return value is just an error indicator like for all runtime functions. You should always check these. (See also Programming Guide chapter 3.2.8)
cudaError_t error = cudaMalloc((void**)&ptr2myDeviceArray, size);

if(error != cudaSuccess) {


  1. You have to pass the pointer to cudaFree by value.
cudaError_t error = cudaFree(ptr2myDeviceArray);

if(error != cudaSuccess) {


  1. You don’t pass to the constructor any size? :huh: