Strange results when calling cudaMemGetInfo

I use the following code the query for available memory:

// Get available memory on graphics card
size_t freeMemory;
size_t totalMemory;
cudaMemGetInfo(&freeMemory, &totalMemory);
printf(“Total memory: %i\nFree memory: %i\n”, totalMemory / 1024 / 1024, freeMemory / 1024 / 1024);

However, sometimes when I run this code I get really strange results, like the following:

Total memory: 2047
Free memory: 133887789

But when I run the program a few minutes later than everything is in order i.e. Free memory < Total memory.

Any clues to why this can happen?


The numbers are bogus as the format specification in the printf does not match it’s arguments. You need to use %z for expressions of type size_t, not %i.

Or, if libc on your computer does not support %z, use a cast:

printf("Total memory: %lu\nFree memory: %lu\n",

           (unsigned long) totalMemory / 1024 / 1024,

           (unsigned long) freeMemory / 1024 / 1024);