c++ - Wrapping pointers into an iterator for copying into an STL container -
i have pointer data want put string. thought using std::copy
should safest approach.
however, in visual studio 2010 warning
warning c4996: 'std::_copy_impl': function call parameters may unsafe - call relies on caller check passed values correct. disable warning, use -d_scl_secure_no_warnings.
and of course warning correct. there checked_array_iterator
objects described on msdn checked_array_iterator can used wrap pointer , make compatible stl iterators.
the problem is, checked_array_iterator
can used target, not source.
so when try use this, application crashes or doesn't compile:
char buffer[10] = "test"; std::string s; // these parameters external call , shown here illustrate usage. char *ptargetadress = &s; const char *obegin = buffer; const char *oend = obegin+sizeof(buffer); std::string *p = reinterpret_cast<std::string *>(ptargetadress); std::copy(obegin, oend, p->begin()); // crash stdext::checked_array_iterator<const char *>beg(obegin, oend-obegin); stdext::checked_array_iterator<const char *>end(oend, 0); std::copy(beg, end, p->begin()); // crash stdext::checked_array_iterator<const char *>v(obegin, oend-obegin); std::copy(v.begin(), v.end(), p->begin()); // doesn't compile
if there portable standard way, rather use instead of reyling on ms extension.
pointers fine (random-access)-iterators. problem lies in copying data bad memory. p->begin()
equal s.begin()
equal s.end()
points invalid memory. fix can use example
std::string *p = reinterpret_cast<std::string *>(ptargetadress); p->resize(oend - obegin); //resize make room data std::copy(obegin, oend, p->begin()); // no more crash
or alternatively
#include <iterator> std::string *p = reinterpret_cast<std::string *>(ptargetadress); std::copy(obegin, oend, std::back_inserter(*p)); // copy appending end
or maybe simply
std::string *p = reinterpret_cast<std::string *>(ptargetadress); *p = std::string(obegin, oend); // copy temporary
Comments
Post a Comment