Segmentation fault in printf?

I’m getting a “Segmentation fault” when I call printf and have been chasing this for hours.

unsigned long long *test;
CUDA_CHECK_RETURN(cudaMallocManaged(&test, sizeof(unsigned long long)); //also tried hard-coding the value of “8” instead of sizeof(…)

printf(“Size: %zu”, sizeof(int)); //Displays 4 (Also same result with %d or %u format specifier
printf(“Size: %zu”, sizeof(unsinged long long)); //Displays 549612246768 or sometimes 548685364880 (same result for uint64_t or other specifiers)

*test = 0;

printf(“%llu”, *test); //Segmentation fault occurs here.

I suspect there’s something else going on, I’m allocating two 2GB blocks using cudaMallocManaged between the declaration and the call to this, but all blocks are uint32_t, float, or unsigned long long (uint64_t).

Presumably you mean to print the value of the pointer (i.e. an address), in which case you would want to use

printf("%p", test);

Dereferencing a null pointer, which is what your code snippet demonstrates, is never a good idea. Your operating system is telling you as much by throwing a seg fault, as yoru user process most certainly doesn’t own the memory at address 0.

I think there is something else going on. To anyone else reading, I modified my original post to include the dereference operator. That was an oversight while typing out my example while getting nagged to take the boat out.

I suspect it has something to do with how I was abstracting some logging. I wrapped printf with a variable arglist to the function and something unexpected was going on.

In that case, double check the use of va_list(), va_start(), va_arg(), and va_end().

If anyone else runs into this, the solution was to use vprintf within the method and not printf. I’ve truncated part of the method signature in this example from my original code and might’ve corrupted something by doing so.

void log(const char *fmt, ...)
{
	va_list args;
	va_start(args, fmt);
	vprintf(fmt, args);
	printf("\n");
	va_end(args);
}

Full sample of benchmark logging. Caveat Emptor:

float previousTotalMilliseconds;
cudaEvent_t startEvents, stopEvents;
void initStartTime()
{
	if (startEvents == NULL)
	{
		printf("Creating events...\n");
		cudaEventCreate(&startEvents);
		cudaEventCreate(&stopEvents);
	}
	else
	{
		printf("Events already created!");
	}
	cudaEventRecord(startEvents);
}

void log(const char *fmt, ...)
{
	cudaEventRecord(stopEvents);
	cudaEventSynchronize(stopEvents);

	float milliseconds;
	cudaEventElapsedTime(&milliseconds, startEvents, stopEvents);
	va_list args;
	va_start(args, fmt);
	printf("[%4.3f - %4.3f] ", milliseconds/1000.0, ((milliseconds - previousTotalMilliseconds) / 1000.0));
	previousTotalMilliseconds = milliseconds;
	vprintf(fmt, args);
	printf("\n");
	va_end(args);
	fflush(stdout);
}