[Solved] SIGABRT called when calling find() on a string element in an array [closed]


It’s pretty simple why it’s crashing when you change that line. In the version that crashes you check whether words[j].find(new_word) is equal to std::string::npos and then call s.erase(s.find(new_word), ...). Of course, s.find(new_word) could still be std::string::npos, and string::erase throws an exception when the first argument is out of range. In the version that you say does not crash, you correctly check whether s.find(new_word) is std::string::npos before passing it to s.erase. It actually has nothing to do with whether you’re using a string in an array or not.

Be it known, though, the variable length array string words[n] is not standard c++, it’s a GCC extension, and so you have to look to them for documentation as to whether all strings are initialized and and whatnot. The standard C++ way to make that array would be string *words = new string[n] followed by delete[] words to free the memory. If you do that, sizeof(words) will be the size of a string pointer, not the allocated size of the array, so you would have to use n instead of sizeof(words) / sizeof(words[0]). The current best-practice would be to use a shared_ptr<string> or a unique_ptr<string> and make_shared or make_unique depending on whether or not you will have multiple aliases to the array. If you use those, you do not have to call delete (or new for that matter); the memory will be freed correctly and automatically when the *_ptr objects go out of scope.

solved SIGABRT called when calling find() on a string element in an array [closed]