0

I recently try to check a substring of another string. The test thought resulting throwing an exception I couldn't quite understand:

#include <string>
#include <iostream>

bool solution(std::string const &str, std::string const &ending) {
  // char string to put the substring from str
  char tmpTest[ending.length()-1];
  
  // copying sub-string the length of ending from str
  std::size_t length = str.copy(tmpTest, ending.length(), str.length()-ending.length());
  // add end of line
  tmpTest[length] = '\0';
    
  if (tmpTest == ending)
    return true;
  else
    return false;

}

with the exception:

Caught std::exception, what(): basic_string::copy: __pos (which is 18446744073709551615) > this->size() (which is 3)

any hints? Thanks..

dboy
  • 1,004
  • 2
  • 16
  • 24
  • 2
    You never check if `str` is longer than `ending`. In this case it isn't. – Yksisarvinen May 16 '22 at 06:36
  • You should [edit] and show a [mcve], IOW wee need to see how you call `solution`. – Jabberwocky May 16 '22 at 06:38
  • 6
    Variable-length arrays are not standard C++. It's unclear why you even need one in this case. It makes the code convoluted and error-prone. Consider using a variant of `std::string::compare`, or if your compiler supports C++20 you can use `std::string::ends_with`. – paddy May 16 '22 at 06:39
  • 1
    Further note that `tmpTest == ending` is actually impossible to return true (apart from cases of undefined behavior) because the array is not even large enough to hold a string the size of `ending`. – paddy May 16 '22 at 06:41
  • well, I've got the problem to understand what the exception trying to tell me, as the code is building and even running. The exception came due a "random" generated test, thus I couldn't provide reproducible example. Any way, it seems to me the first comment provided me the most reasonable hint. @Yksisarvinen: in case you provide your comment as solution, I'd accept it. – dboy May 16 '22 at 07:43

1 Answers1

0

It is not really clear what you want to do, but if I understood correctly, you are checking if string ends with "ending"

Check this website to find working solutions: https://www.techiedelight.com/check-if-a-string-ends-with-another-string-in-cpp/

Šeky
  • 26
  • 3
  • 1
    Answers should be self contained and not rely on external links. – Alan Birtles May 16 '22 at 06:45
  • Or, if you want to refer to an external link, at least refer to another question on StackOverflow, such as [Find out if string ends with another string in C++](https://stackoverflow.com/questions/874134/) – Remy Lebeau May 16 '22 at 08:03
  • Thank you for your input guys.. I will do it next time – Šeky May 16 '22 at 08:49
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 16 '22 at 21:42