QT String to char * adds extra characters












1















I have a qTextEdit that I grab the text from (QString) and convert to a char* with this code:



QString msgQText = ui->textMsg->toPlainText();
size_t textSize = (size_t)msgQText.size();

if (textSize > 139) {
textSize = 139;
}

unsigned char * msgText = (unsigned char *)malloc(textSize);

memcpy(msgText, msgQText.toLocal8Bit().data(), textSize);

msgText[textSize] = '';

if (textSize > 0) {
Msg * newTextMsg = new Msg;
newTextMsg->type = 1; // text message type
newTextMsg->bitrate = 0;
newTextMsg->samplerate = 0;
newTextMsg->bufSize = (int)textSize;
newTextMsg->len = 0;
newTextMsg->buf = (char *)malloc(textSize);
memcpy((char *)newTextMsg->buf, (char *)msgText, textSize);

lPushToEnd(sendMsgList, newTextMsg, sizeof(Msg));

ui->sendRecList->addItem((char *)newTextMsg->buf);

ui->textMsg->clear();
}


I put the text into a qListBox, but it shows up like wrong text



However, the character array, if I print it out, does not have the extra characters.



I have tried checking the "compile using UTF-8" option, but it doesn't make a difference.



Also, I send the text using RS232, and the receiver side also displays the extra characters.



The receiver code is here:



m_serial->waitForReadyRead(200);
const QByteArray data = m_serial->readAll();
if (data.size() > 0) {
qDebug() << "New serial data: " << data;

QString str = QString(data);
if (str.contains("0x6F8C32E90A")) {
qDebug() << "TEST SUCCESSFUL!";
}

return data.data();
} else {
return NULL;
}









share|improve this question

























  • Note that you're writing off the end of the allocated buffer when you do msgText[textSize] = '';. That's undefined behaviour.

    – G.M.
    Nov 13 '18 at 14:32
















1















I have a qTextEdit that I grab the text from (QString) and convert to a char* with this code:



QString msgQText = ui->textMsg->toPlainText();
size_t textSize = (size_t)msgQText.size();

if (textSize > 139) {
textSize = 139;
}

unsigned char * msgText = (unsigned char *)malloc(textSize);

memcpy(msgText, msgQText.toLocal8Bit().data(), textSize);

msgText[textSize] = '';

if (textSize > 0) {
Msg * newTextMsg = new Msg;
newTextMsg->type = 1; // text message type
newTextMsg->bitrate = 0;
newTextMsg->samplerate = 0;
newTextMsg->bufSize = (int)textSize;
newTextMsg->len = 0;
newTextMsg->buf = (char *)malloc(textSize);
memcpy((char *)newTextMsg->buf, (char *)msgText, textSize);

lPushToEnd(sendMsgList, newTextMsg, sizeof(Msg));

ui->sendRecList->addItem((char *)newTextMsg->buf);

ui->textMsg->clear();
}


I put the text into a qListBox, but it shows up like wrong text



However, the character array, if I print it out, does not have the extra characters.



I have tried checking the "compile using UTF-8" option, but it doesn't make a difference.



Also, I send the text using RS232, and the receiver side also displays the extra characters.



The receiver code is here:



m_serial->waitForReadyRead(200);
const QByteArray data = m_serial->readAll();
if (data.size() > 0) {
qDebug() << "New serial data: " << data;

QString str = QString(data);
if (str.contains("0x6F8C32E90A")) {
qDebug() << "TEST SUCCESSFUL!";
}

return data.data();
} else {
return NULL;
}









share|improve this question

























  • Note that you're writing off the end of the allocated buffer when you do msgText[textSize] = '';. That's undefined behaviour.

    – G.M.
    Nov 13 '18 at 14:32














1












1








1








I have a qTextEdit that I grab the text from (QString) and convert to a char* with this code:



QString msgQText = ui->textMsg->toPlainText();
size_t textSize = (size_t)msgQText.size();

if (textSize > 139) {
textSize = 139;
}

unsigned char * msgText = (unsigned char *)malloc(textSize);

memcpy(msgText, msgQText.toLocal8Bit().data(), textSize);

msgText[textSize] = '';

if (textSize > 0) {
Msg * newTextMsg = new Msg;
newTextMsg->type = 1; // text message type
newTextMsg->bitrate = 0;
newTextMsg->samplerate = 0;
newTextMsg->bufSize = (int)textSize;
newTextMsg->len = 0;
newTextMsg->buf = (char *)malloc(textSize);
memcpy((char *)newTextMsg->buf, (char *)msgText, textSize);

lPushToEnd(sendMsgList, newTextMsg, sizeof(Msg));

ui->sendRecList->addItem((char *)newTextMsg->buf);

ui->textMsg->clear();
}


I put the text into a qListBox, but it shows up like wrong text



However, the character array, if I print it out, does not have the extra characters.



I have tried checking the "compile using UTF-8" option, but it doesn't make a difference.



Also, I send the text using RS232, and the receiver side also displays the extra characters.



The receiver code is here:



m_serial->waitForReadyRead(200);
const QByteArray data = m_serial->readAll();
if (data.size() > 0) {
qDebug() << "New serial data: " << data;

QString str = QString(data);
if (str.contains("0x6F8C32E90A")) {
qDebug() << "TEST SUCCESSFUL!";
}

return data.data();
} else {
return NULL;
}









share|improve this question
















I have a qTextEdit that I grab the text from (QString) and convert to a char* with this code:



QString msgQText = ui->textMsg->toPlainText();
size_t textSize = (size_t)msgQText.size();

if (textSize > 139) {
textSize = 139;
}

unsigned char * msgText = (unsigned char *)malloc(textSize);

memcpy(msgText, msgQText.toLocal8Bit().data(), textSize);

msgText[textSize] = '';

if (textSize > 0) {
Msg * newTextMsg = new Msg;
newTextMsg->type = 1; // text message type
newTextMsg->bitrate = 0;
newTextMsg->samplerate = 0;
newTextMsg->bufSize = (int)textSize;
newTextMsg->len = 0;
newTextMsg->buf = (char *)malloc(textSize);
memcpy((char *)newTextMsg->buf, (char *)msgText, textSize);

lPushToEnd(sendMsgList, newTextMsg, sizeof(Msg));

ui->sendRecList->addItem((char *)newTextMsg->buf);

ui->textMsg->clear();
}


I put the text into a qListBox, but it shows up like wrong text



However, the character array, if I print it out, does not have the extra characters.



I have tried checking the "compile using UTF-8" option, but it doesn't make a difference.



Also, I send the text using RS232, and the receiver side also displays the extra characters.



The receiver code is here:



m_serial->waitForReadyRead(200);
const QByteArray data = m_serial->readAll();
if (data.size() > 0) {
qDebug() << "New serial data: " << data;

QString str = QString(data);
if (str.contains("0x6F8C32E90A")) {
qDebug() << "TEST SUCCESSFUL!";
}

return data.data();
} else {
return NULL;
}






qt






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 5:33









AAEM

726318




726318










asked Nov 13 '18 at 14:11









HengyHengy

324




324













  • Note that you're writing off the end of the allocated buffer when you do msgText[textSize] = '';. That's undefined behaviour.

    – G.M.
    Nov 13 '18 at 14:32



















  • Note that you're writing off the end of the allocated buffer when you do msgText[textSize] = '';. That's undefined behaviour.

    – G.M.
    Nov 13 '18 at 14:32

















Note that you're writing off the end of the allocated buffer when you do msgText[textSize] = '';. That's undefined behaviour.

– G.M.
Nov 13 '18 at 14:32





Note that you're writing off the end of the allocated buffer when you do msgText[textSize] = '';. That's undefined behaviour.

– G.M.
Nov 13 '18 at 14:32












1 Answer
1






active

oldest

votes


















1














There is a difference between the size of a QString and the size of the QByteArray returned by toLocal8Bit(). A QString contains unicode text stored as UTF-16, while a QByteArray is "just" a char.



A QByteArray is null-terminated, so you do not need to add it manually.



As @GM pointed out: msgText[textSize] = ''; is undefined behavior. You are writing to the textSize + 1 position of the msgText array.
This position may be owned by something else and may be overwritten, so you end up with a non null terminated string.



This should work:



QByteArray bytes = msgQText.toLocal8Bit();
size_t textSize = (size_t)bytes.size() + 1; // Add 1 for the final ''
unsigned char * msgText = (unsigned char *) malloc(textSize);
memcpy(msgText, bytes.constData(), textSize);


Additional tips:




  • Prefer using const functions on Qt types that are copy-on-write, e.g. use QBytearray::constData() instead of QByteArray::data(). The non-const functions can cause a deep-copy of the object.


  • Do not use malloc() and other C-style functions if possible. Here you could do:
    unsigned char * msgText = new unsigned char[textSize]; and later delete msgText;.


  • Prefer using C++ casts (static_cast, reinterpret_cast, etc.) instead of C-style casts.


  • You are making 2 copies of the text (2 calls to memcpy), given your code only 1 seem to be enough.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53282924%2fqt-string-to-char-adds-extra-characters%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    There is a difference between the size of a QString and the size of the QByteArray returned by toLocal8Bit(). A QString contains unicode text stored as UTF-16, while a QByteArray is "just" a char.



    A QByteArray is null-terminated, so you do not need to add it manually.



    As @GM pointed out: msgText[textSize] = ''; is undefined behavior. You are writing to the textSize + 1 position of the msgText array.
    This position may be owned by something else and may be overwritten, so you end up with a non null terminated string.



    This should work:



    QByteArray bytes = msgQText.toLocal8Bit();
    size_t textSize = (size_t)bytes.size() + 1; // Add 1 for the final ''
    unsigned char * msgText = (unsigned char *) malloc(textSize);
    memcpy(msgText, bytes.constData(), textSize);


    Additional tips:




    • Prefer using const functions on Qt types that are copy-on-write, e.g. use QBytearray::constData() instead of QByteArray::data(). The non-const functions can cause a deep-copy of the object.


    • Do not use malloc() and other C-style functions if possible. Here you could do:
      unsigned char * msgText = new unsigned char[textSize]; and later delete msgText;.


    • Prefer using C++ casts (static_cast, reinterpret_cast, etc.) instead of C-style casts.


    • You are making 2 copies of the text (2 calls to memcpy), given your code only 1 seem to be enough.






    share|improve this answer




























      1














      There is a difference between the size of a QString and the size of the QByteArray returned by toLocal8Bit(). A QString contains unicode text stored as UTF-16, while a QByteArray is "just" a char.



      A QByteArray is null-terminated, so you do not need to add it manually.



      As @GM pointed out: msgText[textSize] = ''; is undefined behavior. You are writing to the textSize + 1 position of the msgText array.
      This position may be owned by something else and may be overwritten, so you end up with a non null terminated string.



      This should work:



      QByteArray bytes = msgQText.toLocal8Bit();
      size_t textSize = (size_t)bytes.size() + 1; // Add 1 for the final ''
      unsigned char * msgText = (unsigned char *) malloc(textSize);
      memcpy(msgText, bytes.constData(), textSize);


      Additional tips:




      • Prefer using const functions on Qt types that are copy-on-write, e.g. use QBytearray::constData() instead of QByteArray::data(). The non-const functions can cause a deep-copy of the object.


      • Do not use malloc() and other C-style functions if possible. Here you could do:
        unsigned char * msgText = new unsigned char[textSize]; and later delete msgText;.


      • Prefer using C++ casts (static_cast, reinterpret_cast, etc.) instead of C-style casts.


      • You are making 2 copies of the text (2 calls to memcpy), given your code only 1 seem to be enough.






      share|improve this answer


























        1












        1








        1







        There is a difference between the size of a QString and the size of the QByteArray returned by toLocal8Bit(). A QString contains unicode text stored as UTF-16, while a QByteArray is "just" a char.



        A QByteArray is null-terminated, so you do not need to add it manually.



        As @GM pointed out: msgText[textSize] = ''; is undefined behavior. You are writing to the textSize + 1 position of the msgText array.
        This position may be owned by something else and may be overwritten, so you end up with a non null terminated string.



        This should work:



        QByteArray bytes = msgQText.toLocal8Bit();
        size_t textSize = (size_t)bytes.size() + 1; // Add 1 for the final ''
        unsigned char * msgText = (unsigned char *) malloc(textSize);
        memcpy(msgText, bytes.constData(), textSize);


        Additional tips:




        • Prefer using const functions on Qt types that are copy-on-write, e.g. use QBytearray::constData() instead of QByteArray::data(). The non-const functions can cause a deep-copy of the object.


        • Do not use malloc() and other C-style functions if possible. Here you could do:
          unsigned char * msgText = new unsigned char[textSize]; and later delete msgText;.


        • Prefer using C++ casts (static_cast, reinterpret_cast, etc.) instead of C-style casts.


        • You are making 2 copies of the text (2 calls to memcpy), given your code only 1 seem to be enough.






        share|improve this answer













        There is a difference between the size of a QString and the size of the QByteArray returned by toLocal8Bit(). A QString contains unicode text stored as UTF-16, while a QByteArray is "just" a char.



        A QByteArray is null-terminated, so you do not need to add it manually.



        As @GM pointed out: msgText[textSize] = ''; is undefined behavior. You are writing to the textSize + 1 position of the msgText array.
        This position may be owned by something else and may be overwritten, so you end up with a non null terminated string.



        This should work:



        QByteArray bytes = msgQText.toLocal8Bit();
        size_t textSize = (size_t)bytes.size() + 1; // Add 1 for the final ''
        unsigned char * msgText = (unsigned char *) malloc(textSize);
        memcpy(msgText, bytes.constData(), textSize);


        Additional tips:




        • Prefer using const functions on Qt types that are copy-on-write, e.g. use QBytearray::constData() instead of QByteArray::data(). The non-const functions can cause a deep-copy of the object.


        • Do not use malloc() and other C-style functions if possible. Here you could do:
          unsigned char * msgText = new unsigned char[textSize]; and later delete msgText;.


        • Prefer using C++ casts (static_cast, reinterpret_cast, etc.) instead of C-style casts.


        • You are making 2 copies of the text (2 calls to memcpy), given your code only 1 seem to be enough.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 13 '18 at 15:29









        Benjamin TBenjamin T

        5,1481127




        5,1481127






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53282924%2fqt-string-to-char-adds-extra-characters%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Florida Star v. B. J. F.

            Danny Elfman

            Lugert, Oklahoma