Home > Net >  C loop breaked 'cause the std::find algorithm
C loop breaked 'cause the std::find algorithm

Time:10-11

I have the next C code snippet:

...
static constexpr const char* my_char_array [10] { // Some literals here... } // Member of a class
std::vector<std::string> splitted_input { // Contains C   strings }
std::vector<std::string> matched_keywords { // The coincident ones will be copied here }

for (int i = 0; i < sizeof(this->my_char_array); i  ) {
    std::cout << "Comparing: " << this->my_char*_array[i] << std::endl;
    auto value = std::find(splitted_input.begin(), splitted_input.end(), (std::string) this->my_char_array[i]);
    if ( value != end(splitted_input) ) {
        matched_keywords.push_back(this->keywords[i]);
    }
}

I am iterating over an const char*, looking for a literal that could be inside a vec<string>. When I use the std::find algorithm, the for loop stops on the first iteration (std::cout just outputs the first value on my_char*_array).

Never faced an issue like that. Any idea?

Thanks in advice.

CodePudding user response:

In this line:

for (int i = 0; i < sizeof(this->my_char_array); i  ) {

you are using sizeof operator which is returning number of bytes which my_char_array occupies, and this is equal to size of pointer (8 bytes on x64 system) multiplied by number of pointers in your array. So this code is iterating over more elements than actually are in you array which is causing UB (undefined behaviour). The usual solution is to divide by element size:

for (int i = 0; i < sizeof(this->my_char_array)/sizeof(this->my_char_array[0]); i  ) {

or even better, replace array with std::array, example:

static constexpr std::array<const char*, 2> my_char_array = {"dsds", "dddd"}; 

and

for (int i = 0; i < my_char_array.size(); i  ) {

and don't forget to #include <array>

  • Related