pinned memory visibility cu & cpp


I wonder if pagelocked memory is visible from the cpu outside the .cu file.
To explain: I call a .cu file from a .cpp file. In .cu file i allocate some bytes of pinned memory where both cpu and gpu read and write.
Can I pass a pointer to that memory as parameter to the .cpp file and have access (read) to pinned memory or is it visible only inside .cu file?
The answer seems yes since the memory is pagelocked but so far I don’t have any success.
Any example code / pseudocode would help.

Yes, pinned memory is just like ordinary memory in that regard. Only if you want to use the pinned memory from other GPUs as well you have to mark it as portable during allocation.

I have only one gpu.
I would like to see an example of how we can read/ write from .cpp file to pinned memory which has been allocated in a .cu file.
If all the code is in .cu file I did it, but I would like to be able to read/ write mapped memory from other functions / other files.
Could anyone post some code or some links to stg relative?

thank you

int *allocate_data(N)


    int *p;

    cudaMallocHost((void**)&p, sizeof(int)*N);

    return p;


int *p = allocate_data(N);

p[i] = 5;

But why do you need to make this convoluted? Just call the cudaMalloc in your .cc files directly.

cudaMallocHost() …

indeed, edited for clarity

I needed an example because this is exactly what I am writing and I get errors related to function types, values etc

Can you post your code and the exact error message you are getting?


int *allocate_memory()


//set flags for mapped memory

HANDLE_ERROR( cudaSetDeviceFlags( cudaDeviceMapHost ) );

// pagelock memory for descriptors

int *descriptors;

HANDLE_ERROR(cudaHostAlloc((void**)&descriptors, 768 * sizeof(int), cudaHostAllocMapped));

// show start address for descriptors

printf("list pointer:%x\n", &descriptors);

return descriptors;


void free_mem(int* k)


//free memory


printf("memory free\n");


file main.cpp

int *allocate_memory();

void free_mem(int* k);

void main()


	int *k=allocate_memory();

	printf("k=%x\n", &k);

	printf("returned to cpp\n");




there is no compiler error but

the value &k is always 72 (dec) less than &descriptors so the pointer doesn’t pass correctly…

printf("list pointer:%lx\n", (unsigned long)descriptors);
printf("k=%lx\n", (unsigned long)k);

You were printing the addresses where the pointers reside in memory, not the addresses they are pointing to.

P.S.: You can post code on the forums between [font=“Courier New”][code][/font]…[font=“Courier New”][/code][/font] tags for the nice formatting as shown above.

You were printing the addresses where the pointers reside in memory, not the addresses they are pointing

Oh! you saved me a few hours :)
thank you very much, everything is fine now