[SOLVED] Calling QString::toWCharArray causes segmentation fault
-
@mcosta I tried with wchar_t __lbl[255], but the problem is the same.
-
Whats the length of
lbl
???I tried this program
#include <QCoreApplication> #include <QtDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QString s = "Super Huge Long long long log string"; const int LABEL_SIZE = 100; wchar_t myLabel [LABEL_SIZE]; qDebug() << s.toWCharArray(myLabel); }
it works, if I change LABEL_SIZE to 20 it crashes.
Which platform?? I'm on OS X
-
@mcosta Ah, I was misunderstanding .. I was unaware of the length of lbl which was 365: So the cause of the segmentation fault is clear here. It is not an OS problem (I'm on GNU/Linux). Changing the length of __lbl to 399 solved the problem.
Thanks. -
Why are you hardcoding the length anyway? What if you decide to use 400 characters one day? You're gonna revisit that code? Just check the length of the string before conversion and allocate enough space for it.
-
@Chris-Kawa Yes, that's true .. using that code instead
__lbl = (wchar_t *)calloc(this->ui->label->text().count(), sizeof(wchar_t));
for allocation is the best way. Thank you for this notice. -
Since you're using c++ I would consider using
new/delete
instead ofcalloc/free
, or, better yet, aunique_ptr
to stay safe of exception problems. Also, according to the standard, names starting with double underscores (and single underscore in global namespace) are reserved for internal compiler/stl implementation. You're stepping on enemy territory using these. -
@Chris-Kawa I'm mainly a C programmer, I don't like using C++ if not for widget programming .. anyway, what does "reserved for internal compiler/stl implementation" mean?
-
anyway, what does "reserved for internal compiler/stl implementation" mean?
Means that such names are not to be used by users (us). They are reserved for compilers and STL.
For example the standard__LINE__
,__FILE__
and__func__
macros, or the vendor specific keywords like MSVC's__super
.This restriction is not enforced by any compiler I know, but technically you shouldn't name your stuff this way and implementation is free to do with that code whatever it wants (undefined behavior in user space).
-
@Chris-Kawa Yes, that's true .. but I'm quite careful about that, and I have enough experience in C Programming with GNU development tools such as GCC.
-
Yeah, and I'm not saying that it will ever break. I can't imagine any compiler doing anything malicious to such code. I'm just saying it's standard non-conforming code.