我有一个关于cudaFree
的工作方式的问题.在下面的代码中,为了在设备上分配数组,cudaMalloc
需要数组的地址.这是通过使用&array_d
完成的.
int *array_d;
cudaMalloc((void**)&array_d, sizeof(int) * 100);
cudaFree(array_d);
从逻辑上讲,当我们想要释放内存时,我们还必须将数组地址传递给cudaFree
.否则,它如何知道必须释放内存的哪一部分呢?
我有一个关于cudaFree
的工作方式的问题.在下面的代码中,为了在设备上分配数组,cudaMalloc
需要数组的地址.这是通过使用&array_d
完成的.
int *array_d;
cudaMalloc((void**)&array_d, sizeof(int) * 100);
cudaFree(array_d);
从逻辑上讲,当我们想要释放内存时,我们还必须将数组地址传递给cudaFree
.否则,它如何知道必须释放内存的哪一部分呢?
array_d
是一个指针,用于保存分配的内存块的地址(在本例中包含int
).
This address is actually determined by cudaMalloc
, and therefore you need another level of indirection when calling it.
This is why you pass &array_d
which is the address of the pointer itself (not the address of the pointed memory block), and cudaMalloc
fills it with the address of the newly allocated block.
cudaFree
indeed requires this address, to know which memory block to free.
But it does not modify this address. Therefore it is sufficient to pass array_d
itself (as it holds this address).
下图说明了3个实体之间的关系:
+----------+ +----------+
| &array_d | -> | array_d | -> memory block on GPU
+----------+ +----------+
注意,array_d
是保存驻留在GPU memory中的存储块的地址的指针.但是指针本身存储在host memory中(在本例中存储在堆栈上).
&array_d
是该指针的地址(即host memory中的地址).