Printf with const char * variable

I am stuck in printf problem. I would appreciate it if I could get help here: In the code below, I see that the font family moves correctly in the first printf (), but if I set it to a variable, I get only an empty string. How can I put it in a variable and have the correct values? I just don't want to type 'font.family (). Family (). String (). Utf8 (). Data () 'everywhere?

I did this using the same method:

void myMethod() { const char* fontFamily = font.family().family().string().utf8().data(); // get displayed correctly printf ("drawText1 %s \n", font.family().family().string().utf8().data()); // get an empty string printf ("drawText2 %s \n", fontFamily); } 

And the signature 'data ()' is

 class CString { public: CString() { } CString(const char*); CString(const char*, unsigned length); CString(CStringBuffer* buffer) : m_buffer(buffer) { } static CString newUninitialized(size_t length, char*& characterBuffer); const char* data() const; //... } 

Utf8 () signature is

 class String { CString utf8() const; } 

Thanks.

+6
c ++ printf
source share
3 answers

Something in the chain of font.family().family().string().utf8().data() returns a temporary object. In the first printf temporary object does not go out of scope until printf returns. In the second, printf temporary is destroyed after the pointer is assigned, and the pointer is now invalid. You see a classic example of undefined behavior.

There are two ways to fix this. Either make a copy of the data before temporary destruction, or make a link to a temporary one. A copy is probably the simplest and clearest if the class has a copy statement. Assuming utf8() creates a temporary CString , this will be

 CString fontFamily = font.family().family().string().utf8(); printf ("drawText2 %s \n", fontFamily.data()); 
+4
source share

You are caching a pointer that is in the temporary return of utf8() (as Mark and Neil claimed). You will need to change fontFamily to CString or const CString & to keep the result from utf8() in scope.

+1
source share

Calling data() (assuming it is called on std :: string) does not necessarily return a string with a terminating zero. You almost certainly want c_str() , which is defined for this.

0
source share

All Articles