Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting Segmentation violation signal error on copying vector elements?

I have the following code for doing a http post request. I am getting the response in
const std::vector<json> value …The below code works correctly

RpcResponseAndContext<std::vector<Largest>>
Connection::getLargestAccounts() const {
  const json params = {};
  const auto reqJson = jsonRequest("getLargest", params);
  const json res = sendJsonRpcRequest(reqJson);
  const std::vector<json> value = res["value"];
  std::vector<Largest> accounts_list;
  accounts_list.reserve(value.size());
  for (const json &account : value) {
    accounts_list.push_back(account);
  }
  return {res["context"], accounts_list};
}

To improve the appending of elements into accounts_list vector..I am trying to use std::copy()
But getting this error: FATAL ERROR: test case CRASHED: SIGSEGV – Segmentation violation signal

I am trying this way:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

RpcResponseAndContext<std::vector<Largest>>
Connection::getLargestAccounts() const {
  const json params = {};
  const auto reqJson = jsonRequest("getLargest", params);
  const json res = sendJsonRpcRequest(reqJson);
  const std::vector<json> value = res["value"];
  std::vector<Largest> accounts_list;
  accounts_list.reserve(value.size());
  std::copy(value.begin(), value.end(), accounts_list.begin());
  return {res["context"], accounts_list};
}

What I am doing wrong ?

>Solution :

reserve does not resize the vector, it just pre-allocates the space so push_backs are cheap and never invalidate any iterators but they are still required.

std::copy assumes (like most <algorithm>s) the output iterators are valid, i.e. point to existing location. In this case they do not.

What you need is std::back_inserter which will call push_back for you:

accounts_list.reserve(value.size()); // Optional optimization
std::copy(value.begin(), value.end(), std::back_inserter(accounts_list));

I am not actually sure whether this is the cause since you did not provide a minimal reproducible example, I would expect some iterator assertion, not segfault since the memory should have been allocated. Maybe some empty std::vector optimization is at play.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading