TR3M4 TR3M4 - 3 months ago 18
C++ Question

Crashing while converting string to wstring

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 &regExp, 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.

Answer

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.

Comments