Thursday, November 1, 2012

String to Number Conversions

As the modified Parser code was being tested, a weird memory issues was reported by valgrind.  The problems occurred with the toInt() and toDouble() functions of QString.  The problem was duplicated with a very simple program:
#include <QString>
int main(void) {
    qDebug("%d", QString("123").toInt();
}
The same issue occurs if the program above is changed to double with toDouble().  No reason for this error could be found.  However, when this program is turned into a Qt console application, the error no long occurred.  But this same thing applied to the ibcp program did not eliminate the error.  Click Continue... for how to build and run this program from the command line to demonstrate the memory issue (requires Linux with Qt and valgrind installed).

No solution was found for this problem.  When the program was changed from QString to QByteArray, which also contains these same two functions, no memory issue was reported.  Therefore, as a temporary solution, the string to convert is converted to a QByteArray.  A QByteArray was declared and the QString to convert was appended to it.

Build Test Program

Create a new directory for the above program and change into it.  Put the above program into a source file named main.cpp.  A Qmake (project) file needs to be generated that will create a make file that will build the program.  Fortunately, the qmake executable can do these steps automatically.  Use these commands:
qmake -project
qmake
make
An executable will be create with the same name of the directory that was created.  To run the program through valgrind, issue this command:
valgrind --leak-check=full <executable-name>
The two memory lost (leak) issues will be reported.  After changing QString to QByteArray in this program and building (make), valgrind no longer reports any memory issues.

No comments:

Post a Comment

All comments and feedback welcomed, whether positive or negative.
(Anonymous comments are allowed, but comments with URL links or unrelated comments will be removed.)