Problem on STL copy()
Hi, why does this following code fragment produce segfault? ========================================== #include <iostream> #include <algorithm> #include <vector> using namespace::std; void fillVector(vector<string>& v); int main() { vector<string> src; fillVector(src); vector<string> dst; // ====>> The following copy() is the culprit <<==== copy(src.begin() + 1, src.end(), dst.begin()); return 0; } void fillVector(vector<string>& v) { v.push_back("field_A"); v.push_back("field_B"); v.push_back("field_C"); } ========================================== -- +++ GMX - Mail, Messaging & more http://www.gmx.net +++ Jetzt ein- oder umsteigen und USB-Speicheruhr als Prämie sichern!
Verdi March wrote:
why does this following code fragment produce segfault?
vector<string> dst;
// ====>> The following copy() is the culprit <<==== copy(src.begin() + 1, src.end(), dst.begin());
In this case you would need vector<string> dst( src.end() - src.begin() + 1 ); to ensure that there are elements to overwrite. copy doesn't use, for example, push_back() if there isn't space to copy to. Hence the segfault. Come to think of it, this makes copy poor for reading input streams because there's nothing to prevent buffer overrun. -- JDL Non enim propter gloriam, diuicias aut honores pugnamus set propter libertatem solummodo quam Nemo bonus nisi simul cum vita amittit.
On Friday 11 July 2003 07:09, Verdi March wrote:
Hi,
why does this following code fragment produce segfault? ========================================== #include <iostream> #include <algorithm> #include <vector> using namespace::std;
void fillVector(vector<string>& v);
int main() { vector<string> src; fillVector(src);
vector<string> dst;
The destination container must be big enough!
// ====>> The following copy() is the culprit <<==== copy(src.begin() + 1, src.end(), dst.begin());
Or use this: copy(src.begin() + 1, src.end(), back_inserter( dst));
return 0; }
void fillVector(vector<string>& v) { v.push_back("field_A"); v.push_back("field_B"); v.push_back("field_C"); }
participants (3)
-
John Lamb
-
Sebastian Huber
-
Verdi March