Rafael Adel
Rafael Adel

Reputation: 7759

Getting “./a.out” terminated by signal SIGSEGV (Address boundary error)

I'm writing a program that splits any two numbers. The problem is whenever I run the program I get an error that says:

“./a.out” terminated by signal SIGSEGV (Address boundary error)

And that error occurs at the lines:

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

and

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

Here's my program:

#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));
}

Any help would be appreciated.

Upvotes: 0

Views: 861

Answers (1)

Michael Koenig
Michael Koenig

Reputation: 364

You get the segmentation fault because your vector is empty. Your vector is empty because you pass a copy of your initial vector to split_number(). The copy is passed because the signature of split_number() says it requires a copy. Change it to:

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

The ampersand makes the vect parameter a reference parameter, and modifications will show in the calling code.

Upvotes: 3

Related Questions