lundi 26 juin 2023

const std::string::size() is much larger than it should be in optimization level 2

Definition:

const std::string a_class::dft_col_name{"NONE"};

Usage:

in a_class::function()

just loop one time, i is 0

for (int i = 0; i < result->colnum; ++i) {
    result->pcolname[(i + 1) * SQLCOLLEN - 1] = '\0';
    auto colname_len = strlen(result->pcolname + i * SQLCOLLEN);
    if (colname_len == 0) {
        // given column name if there isn't
        strcpy(result->pcolname + i * SQLCOLLEN, dft_col_name.c_str());
        colname_len = dft_col_name.size();

        /*!! Confusion !!*/

        std::cout << dft_col_name << '\n';
        // O2 print: lots of corrupted text
        std::cout << dft_col_name.c_str() << '\n';
        // O2 print: "NONE"
        printf("%lu %lu %s\n", colname_len, dft_col_name.size(), dft_col_name.c_str());
        // -g O0 print: 4 4 NONE
        // O2 print: 17179869184 17179869184 NONE

    }
    result->plen[i] = colname_len;
}

Environment:

Linux version 3.10.0-1062.12.1.el7.x86_64 (mockbuild@kbuilder.bsys.centos.org)
(gcc version 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) ) #1 SMP Tue Feb 4 23:02:59 UTC 2020

g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

I'm really confused about it!

I tried using valgrind --tool=memcheck to debug, and no Invalid write was found.

I tried relacing const std::string to const char[], dft_col_name.size() to strlen(), and it worked.

Aucun commentaire:

Enregistrer un commentaire