0

So I have two simple classes, one cleaning unwanted values from vector and second one calling the first one. At the end I'm getting value from std::optional. That's it. It works fine with small sets but if I call test with vector.size() around 300 and more the program gets stuck on auto c = *b; and terminates application with returns 3 code. Does any one have any idea what might be the cause?

std::vector<uint8_t>
getMessageFromStartSignToEndSign(std::vector<uint8_t> message, uint8_t startSign, uint8_t endSign,
                                 bool areStartAndStopSignsLeftInResultStream) {
    bool wasMsgUpdated = false;
    while (*message.cbegin() != startSign) {
        message.erase(message.begin());
    }
    //-2 'cause after etx sign 0x03 is crcSum
    while (*(message.cend() - 2) != endSign) {
        message.erase(message.end() - 1);
    }

    if (!areStartAndStopSignsLeftInResultStream) {
        message.erase(message.begin());
        message.erase(message.end() - 1);
    }

    return message;
}

std::optional<std::vector<uint8_t>> test(std::vector<uint8_t> val){
    return getMessageFromStartSignToEndSign(val,0x02,0x03,true);
}

main.cpp

int main() {
    std::vector<uint8_t> a = {0x01,0x01,0x01,0x01,0x01, 0x02, 0x3, 0x25, 0x65, 0x03, 0x02};
    for(int i = 0; i< 120;i++){
        a.insert(a.end(),a.begin(),a.end());
    }
    auto b = test(a);
    auto c = *b;
    std::cout<<"size = "<<c.size()<<std::endl;
    return 0;
}
Gameriker
  • 35
  • 7
  • 1
    You can't insert a vector into itself; each time you add an element, all iterators are invalidated. See https://stackoverflow.com/questions/17636690/nice-way-to-append-a-vector-to-itself for other ideas. However, a more serious problem is that you appear to be doubling the vector `a` 120 times. Its length at the end would be 11*2**120 = 14621507953634074601941877663083790336 bytes. Pretty sure you don't have that much memory. – Nate Eldredge Nov 12 '21 at 23:14
  • If your goal is to have a vector containing 120 copies of `a` (not 2**120 copies), then you could just make a new empty vector and insert `a` into it 120 times. `std::vector x; for(int i = 0; i< 120;i++) { x.insert(x.end(), a.begin(), a.end()); } auto b = test(x);` – Nate Eldredge Nov 12 '21 at 23:18

0 Answers0