I got the following function that crashes randomly when converting a string to a wstring. It is used to parse HTTP headers ( http://www.codeproject.com/Articles/66625/A-Fully-Featured-Windows-HTTP-Wrapper-in-C ) and always worked fine, but it randomly stopped working when I changed server recently. (This code comes from the classes that comes with the codeproject project)
inline bool ParseRegExpW(const wstring ®Exp, bool caseSensitive, int groupCount, const wstring &source, vector<wstring> &result, bool allowDuplicate = false)
{
const string regEXP = string(regExp.begin(), regExp.end());
const string Source = string(source.begin(), source.end());
vector<string> Result;
if (result.size() != 0){
for (int i = 0; i < result.size(); i++) {
Result[i] = string(result[i].begin(), result[i].end());
}
}
bool res = ParseRegExp(regEXP, caseSensitive, groupCount, Source, Result, allowDuplicate);
if (Result.size() != 0){
for (int i = 0; i < Result.size(); i++) {
printf("Result: %i->%s L: %i : R %i r %i\n", i, Result[i].c_str(), Result[i].length(), Result.size(), result.size());//Result[i] contains what it should contain
if (i < Result.size()){
printf("Converting...\n");
result[i] = wstring(Result[i].begin(), Result[i].end());
printf("Will crash before getting there..\n");
}
}
}
return res;
}
Why is this happening? It's so weird to me that it was working fine for the last months and stopped working when I changed server.
Assuming result.size() == 0
, when you get into that loop and to ...
result[i] = wstring(Result[i].begin(), Result[i].end());
... then no matter the value of i
, you'll get undefined behavior due to accessing a non-existent element of the vector.
If result.size() != 0
, then this code path will be executed, ...
vector<string> Result;
if (result.size() != 0){
for (int i = 0; i < result.size(); i++) {
Result[i] = string(result[i].begin(), result[i].end());
}
}
... which has the same issues in regard to the empty vector Result
.
I'm wondering how this could've ever worked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.