[Qt-interest] Segmentation fault while converting from QString to char*

Ross Driedger ross at earz.ca
Mon Apr 19 18:14:28 CEST 2010


On 19-Apr-10, at 4:00 AM, qt-interest-request at trolltech.com wrote:

> Message: 3
> Date: Mon, 19 Apr 2010 15:10:43 +0530
> From: prashant bhutani <prashantbhutani2008 at gmail.com>
> Subject: Re: [Qt-interest] Segmentation fault while converting from
> 	QString	to char*
> To: qt-interest at trolltech.com
> Message-ID:
> 	<x2wca3e66fb1004190240yed370232oe8b7014dd481ca5e at mail.gmail.com>
> Content-Type: text/plain; charset="windows-1252"
>
> Hi,
> sorry for previous one.
> On using statement, *char *cstr = qstr.toStdString.c_str();*
> i got *?qt_file_name.QString::toStdString? does not have class type*

As someone has pointed out, the 'toStdString' is a function call, so  
it has to be:
toStdString()

Be very careful, with your const correctness:

char *cstr = qstr.toStdString().c_str();

should, at the very least, give you a compiler warning  c_str()  
returns a const char* and this pointer is only valid as long as the  
string is in scope.  In my experience, const correctness is a vital  
subject that most c++ courses gloss over if not entirely ignore.  If  
you really need to make it into a non-const C string than you have to  
make a copy of it:

const char *cstr = qstr.toStdString().c_str();
//buffer is a valid char array that is long enough to hold the  
contents of the string
strcpy(cstr, buffer);

Please note that this code is NOT safe and I leave the proper error  
checking as an exercise.

All that said, there is usually no reason to do this kind of  
conversion in c++: anything that can be done with a char array can be  
done with QString or std:;string.

-- 
"Without music to decorate it, time is just a bunch of boring  
production deadlines or dates by which bills must be paid."
Frank Zappa

Ross Driedger
ross (at) earz (dot) ca



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20100419/e433b941/attachment.html 


More information about the Qt-interest-old mailing list