No, this is not currently allowed in OpenCL.
You could implement your own heap by creating one very large buffer up front, and then 'allocate' regions of the buffer by handing out offsets (using atomic_add
to avoid synchronisation issues). However, in most cases I suspect it would be better just to rethink your algorithm and come up with an approach that doesn't require dynamic memory allocation in the first place.
Here's an example that uses a preallocated buffer to emulate dynamic heap allocation inside kernels. The heap and index of the next free element are passed into the kernel as arguments, and need to passed onto our malloc
function. In OpenCL 2.0, we could use program scope global variables to avoid the need to do this.
global void* malloc(size_t size, global uchar *heap, global uint *next)
{
uint index = atomic_add(next, size);
return heap+index;
}
kernel void foo(global uchar *heap, global uint *next)
{
// Allocate some memory from heap
global void *data = malloc(4, heap, next);
...
}