mardi 27 octobre 2020

Why using string results in exit code 3 and using char[] doesnt

I'm practicing my coding skills and I was solving the following backtracking problem (the solution of the original guide is in there as well)

Summary of the problem: Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them.

My solution is the following:

#include <iostream>
#include <cstring>
#include <string>


using namespace std;

void permutationWithSpacesAux(const char* s, string buf, int s_index, int b_index, int len_s){

    // stop condition
    if(s_index == len_s){
        cout << buf << endl;
        return;
    }
    // print w\o space
    buf[b_index] = s[s_index];
    // recursive call w\ next indices
    permutationWithSpacesAux(s, buf, s_index + 1, b_index + 1, len_s);

    // print w\ space
    buf[b_index] = ' ';
    buf[b_index + 1] = s[s_index];
    // recursive call w\ next indices
    permutationWithSpacesAux(s, buf, s_index + 1, b_index + 2, len_s);
}

void permutationWithSpaces(const char* s){
    int n = strlen(s);
    string buf;
    buf.reserve(2*n);
    buf[0] = s[0];
    permutationWithSpacesAux(s,buf, 1, 1,n);
}

int main() {
    const char* s = "ABCD";
    permutationWithSpaces(s);
    return 0;
}

This is the Error I've got:

C:\Users\elino\CLionProjects\permutationWithSpaces\cmake-build-debug\permutationWithSpaces.exe
/home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libstdc++-v3/include/bits/basic_string.h:1067: std::__cx
x11::basic_string<_CharT, _Traits, _Alloc>::reference std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator[](st
d::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type) [with _CharT = char; _Traits = std::char_traits<char>; _Al
loc = 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.

Process finished with exit code 3

My solution is very similar to the guide's solution, only that I used std::string for the buffer variable instead of char[] as the guide did. I'm trying to understand what property of the std::string class could raise this problem? From what I found online I think I accessed an illegal place in the memory when trying to access a string character, and I think the problem rises from the way that I reserved space in the memory for buf. I want to gain a deeper understanding of the problem, and I'll appreciate it if someone could further explain where it rises from.

Thank you.

Aucun commentaire:

Enregistrer un commentaire