Search code examples
c++visual-studio-codegccruntime-errorstdstring

Run time error: "/home/keith/builds/mingw/gcc........" in VS Code while working with strings


My code is running properly in other online C++ compilers but throws an unexpected error in VS Code. Please find the bug in my code.
VS Code Version - 1.74.3

CODE:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string input;
    int size;
    cout << "Enter the size of your string value" << endl;
    cin >> size;
    cout << "Enter the string whose first letter has to be changed" << endl;

    for (int i = 0; i < size; i++) {
        cin >> input[i];
    }

    input[0] = 'Z';
    cout<< "The changed string is ";

    for (int i = 0; i < size; i++) {
        cout << input[i];
    }

    return 0;
}

TERMINAL:

    Enter the size of your string value
    4
    Enter a string whose first letter has to be changed
    moya

ERROR:

/home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libstdc++- 
v3/include/bits/basic_string.h:1067: std::__cxx11::basic_string<_CharT, _Traits, 
_Alloc>::reference std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator[] 
(std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type) [with _CharT = char; 
_Traits = std::char_traits<char>; _Alloc = std::allocator<char>; 
std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference = char&; 
std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type = unsigned int]: 
Assertion '__pos <= size()' failed.

Solution

  • string input; is empty so input[i] accesses the string out of bounds which makes your program have undefined behavior. You could resize it to size to make it work - or create the string with the correct size after you've entered what size you want it to have.

    Example:

    #include <iostream>
    #include <string>
    
    int main() {
        std::string input;
        int size;
        std::cout << "Enter the size of your string value\n";
        if(std::cin >> size && size > 0) {
    
            input.resize(size); // resize the string
            // std::string input(size, '\0'); // or create it here with the correct size
    
            std::cout << "Enter the string whose first letter has to be changed\n";
    
            for(char& ch : input) { // a simpler range-based for loop
                std::cin >> ch;
            }
            input[0] = 'Z';
            std::cout << "The changed string is ";
            std::cout << input << '\n'; // no need to loop here
        }
    }