intmain(){ std::cout << "Enter some text: "; std::string text; if (!std::getline(std::cin, text)) { std::cout << "Failed to read text\n"; return1; } std::cout << "Enter a placeholder: "; std::string placeholder; if (!std::getline(std::cin, placeholder)) { std::cout << "Failed to read placeholder\n"; return1; } std::cout << "Enter the index of the stuff to redact: "; int index; if (!(std::cin >> index)) { std::cout << "Failed to read index\n"; return1; } if (index < 0 || index > text.size() - placeholder.size()) { // [*] std::cout << "Invalid index\n"; return1; } std::copy(placeholder.begin(), placeholder.end(), text.begin() + index); // [**] std::cout << text << '\n'; }
Look at the [*]. The text.size() and placeholder.size() are size_t. It means unsigned. But index is just int. If text.size() is 0 and placeholder.size() is 8, the result of text.size() - placeholder.size() is normally -8(When it is signed..). But it is not. Becuase of their type is unsigned, the result of that is very big int.
If text is stored in stack, it can cause the BOF at [**]. We can trigger this, but We need to know the how std::string is stored in memory.
Here is the structure of that std::string is stored in memory.