简体   繁体   中英

std::string::erase causes memory corruption

I am sitting on this error for over 20 minutes and I can't spot anything erroneous. std::string::erase is causing the error.

#include <iostream>
#include <string>
#include <cctype>

template <typename ForwardIt>
std::string trimLeft(std::string string_, ForwardIt begin_, ForwardIt end_)
{
    if (!string_.empty())
    {
        auto it = begin_;
        while (it != end_ && std::isspace(static_cast<unsigned char>(*it)))
            ++it;

        string_.erase(begin_, it);
    }
    return string_;
}

std::string trimLeft(std::string string_)
{
    return trimLeft(string_, string_.begin(), string_.end());
}

int main() {
    std::string str{"   left"};
    // Note: this code would work:
    // str.erase(str.begin(), str.begin() + 3);
    std::cout << "|" << trimLeft(str) << "|" << std::endl;
    std::cout << "|" << trimLeft(std::string{"z left"}) << "|" << std::endl;
    std::cout << "|" << trimLeft(std::string{"\tleft"}) << "|" << std::endl;
}

Take a careful look at your signature:

template <typename ForwardIt>
std::string trimLeft(std::string string_, ForwardIt begin_, ForwardIt end_)
//                   ~~~~~~~~~~~~

string_ is a value, a new copy of the string you're passing in. begin_ and end_ are iterators into... an entirely different string. So when you try to erase :

string_.erase(begin_, it);

You're violating the preconditions that begin_ is actually an iterator into string_ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM