Should I free buffer data?

I’d like to know how best to treat memory that I’m using for mapped buffer data after I’ve unmapped the buffer. For instance:

float* my_data;
rtBufferMap(my_buffer, (void**)&my_data);
rtBufferUnmap(my_buffer);
do_stuff_with(my_data);
free(my_data); // <== Should I do this?

If I’m going to call the above code frequently, then I’d like to avoid memory leaks from repeatedly mapping the buffer to new memory. However, sometime when I try to free the memory, I get an error that the pointer is not a valid heap pointer. What’s the best practice here? Does rtBufferMap malloc the memory for my_data internally, or is something completely different at work here?

Sorry, that code isn’t correct. An application crash is to be expected.

The pointer you get from an rtBufferMap() operation is only valid until you called rtBufferUnmap() on the same buffer.
You must neither access the data behind that pointer while it’s not mapped, nor is it allowed to call some free() operation on it.

Please follow the example in the OptiX API Reference or any OptiX sample using rtBufferMap().
This would be your legal code:

float* my_data;
rtBufferMap(my_buffer, (void**)&my_data);
    do_stuff_with(my_data);
rtBufferUnmap(my_buffer);

(Another case would be CUDA interop buffers which use device side pointers where the update happens through CUDA device code. Then you’d need to make the buffer dirty manually to let OptiX know its contents have changed, to be able to rebuild accelerations structures etc.)