信号SIGSEGV终止“./a.out”(地址边界错误)

时间:2016-08-22 14:11:06

标签: c++11 memory declaration

我正在编写一个分割任意两个数字的程序。问题是每当我运行程序时,我都会收到错误消息:

  

“./ a.out”由信号SIGSEGV(地址边界错误)终止

该错误发生在以下行:

a = std::stoi(temp_vec.front());
b = std::stoi(temp_vec.back());

c = std::stoi(temp_vec.front());
d = std::stoi(temp_vec.back());

这是我的计划:

#include <iostream>
#include <string>
#include <vector>

void split_number(std::vector<std::string> vect, int x);

int main()
{
  int x = 0, y = 0, a = 0, b = 0, c = 0, d = 0;
  std::vector<std::string> temp_vec;

  std::cout << "Enter x: ";
  std::cin >> x;
  std::cout << "Enter y: ";
  std::cin >> y;

  split_number(temp_vec, x);
  a = std::stoi(temp_vec.front());
  b = std::stoi(temp_vec.back());

  split_number(temp_vec, y);
  c = std::stoi(temp_vec.front());
  d = std::stoi(temp_vec.back());

  return 0;
}

void split_number(std::vector<std::string> vect, int x)
{
  vect.clear();

  //1. convert x to string
  std::string temp_str = std::to_string(x);

  //2. calculate length
  std::size_t len = temp_str.length();
  std::size_t delm = 0;
  if(len % 2 == 0) {
    delm = len / 2;
  } else {
    delm = (len + 1) / 2;
  }

  //3. populate vector
  vect.push_back(temp_str.substr(0, delm));
  vect.push_back(temp_str.substr(delm + 1));
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:3)

您的矢量为空,导致分段错误。您的向量为空,因为您将初始向量的副本传递给split_number()。传递副本是因为split_number()的签名表示它需要副本。将其更改为:

void split_number(std::vector<std::string> & vect, int x)

&符号使vect参数成为引用参数,修改将显示在调用代码中。

相关问题