C ++ Why does the sprintf_s format change when used with a void pointer?

This is valid source code:

// ... unsigned __int64 num = 57; sprintf_s(buffer, sizeof(buffer), "%llu", num); 

However, when I try to extract this part into this function:

 void addBuffered(void** attributeValue, char* format) { sprintf_s(buffer, sizeof(buffer), format, *attributeValue); } 

causing:

 addBuffered((void**)&num, "%d"); 

I need to change the format parameter in sprintf_s from %llu to %d to get the correct value. Can someone explain why this is happening, and is there a problem with changing the parameter to %d ? Thanks!

+4
source share
3 answers

This is because sizeof(void *) == 4 in your case. And you implicitly throw __int64 at void * on function call. Therefore, if you use the %llu format, you print some garbage from memory.

I suggest you rewrite the function if possible:

 template <typename T> void addBuffered(T *attributeValue, char* format) { sprintf_s(buffer, sizeof(buffer), format, *attributeValue); } 

Call example:

 addBuffered(&num, "%luu"); 
+5
source

I suggest making it simple:

 std::ostringstream buffer; buffer << num; 

Even if they can be cumbersome to internalize / customize; for simple formatting streams is very simple ... and safe .

+1
source

You can safely use %p as the appropriate printf format specifier for values ​​of type void * .

Of course, with that said, I also recommend that you explore a safer implementation here. Is there a reason your addBuffered function addBuffered not a variable? You can use vsprintf_s instead.

0
source

All Articles