Memory Error with std:ostringstream and -std=c++11? [duplicate]

不想你离开。 提交于 2019-11-29 16:48:46
const char* stmt = qs.str().c_str();

That extracts a temporary string from qs, takes a pointer to its content, then destroys the temporary leaving the pointer dangling. Using the pointer after this will give undefined behaviour.

To fix it, you could either assign the result of str() to a variable, so that it's no longer temporary, or use this expression as the argument to sqlite3_exec, so that the temporary survives until after that function call. (In the second case, you'd have to remove the first assertion; but that assertion is rather pointless anyway).

Take a closer look at this line: const char* stmt = qs.str().c_str();

qs.str() provides you a temporary std::string object from which you take a pointer to inner char* array. Once this line completes its execution, your pointer is no longer valid and something else may (and probably is) stored there.

Try doing this instead:

std::string strstmt(qs.str());
const char* stmt = strstmt.c_str();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!