I was asked to make a copy of std::string in an assignment and I am having problem implementing the substr function. In a set of tests the teacher gave us there was one with a length equal to -1. Mine declaration of substr is:
Cadena substr(size_t start, size_t length) const;
Which I (thought) that the size_t would prevent negative values to be passed. The problem is that in the definition I check for size() < start + length (assume tam_ is the same as size()):
if (tam_ < start + length)
throw std::out_of_range("Error");
In my system -1 in unsigned is 18446744073709551615, so that, for example assume start is 9 and tam_ is 10.
I expect:
10 < 9 + 18446744073709551615
So that the exception is thrown, but in reality I get
10 < 9 + (-1)
Which is false and exception isn't thrown. As the function continues it allocates a char array for size length + 1, which the system refuses due to that new[] threats the size_t as it should be, 18446744073709551615, which is so big and make the program crash.
I want to know why my expected result isn't the correct.
Thanks
Aucun commentaire:
Enregistrer un commentaire