search

Home  >  Q&A  >  body text

c++ - 一个wprintf在x86和x64下的不同表现

就是一个简单的wprintf,在x86 build中可以输出正确,但在x64 build就会乱码
一段比较老的code要维护,当时的前提就是m_str是第一个变量,然后指向MyStr指针会指向它,wprintf会将指向字符串的指针作为%s 输出,但是在X64下,传递给wprintf的却是指向一个Mystr的指针,导致乱码。
目前的解决方案就是强制转换,但是我想知道具体的原因

#include <iostream>
using namespace std;

class MyStr
{
public:
    wchar_t * m_str;
    int length;


	MyStr(wchar_t* str)
	{
		m_str = str;
        length = 2147483647;
	}

	operator const wchar_t*() const
	{
		return m_str;
	}
};



int main()
{
    wchar_t * str = L"hello";
	MyStr s1(str);
    
    wprintf(L"%s",s1);
	wprintf(L"%s",(const wchar_t*)s1);
	return 0;
}
天蓬老师天蓬老师2803 days ago548

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 11:04:37

    It’s very strange what kind of programmer would write such weird code that is completely unreasonable and purely relies on the memory layout of objects.
    Let’s take a look at the memory layout of the s1 object under x86. The object s1 occupies 8 bytes. The first four bytes are the pointer m_str, and the last four bytes are the integer length. When the wprintf sentence is executed, length will be first Push on the stack, then m_str, and finally L"%s". This wprintf just outputs the string pointed to by m_str and returns it. The length is simply discarded. You can try wprintf(L"%s %d ", The output result of s1). At this time, you should thank God. If there is a virtual function table, it will collapse under x86. But you can also try to reverse the order of m_str and length, which will crash again...
    As for forced type conversion under x64, I guess it is the length of the pointer. I am not familiar with x64, so I won’t talk nonsense.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 11:04:37

    http://www.cplusplus.com/reference/cl...

    wprintf(L"%ls",(const wchar_t*)s1);

    reply
    0
  • Cancelreply