vector empty() segmentation fault

Sep 1, 2016 at 12:28am
Hi,

I have a class , MyList. it contains a vector but I keep getting segmentation fault try to return the vector.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void MyList::setList(std::vector<std::string> list)
{
    list = list;
}

std::vector<std::string> MyList::getList()
{
    return list;
}

void MyList::addNewElement(std::string newElement)
{
    if(getList().empty())
    {
	......
    }
............
}


The .h file have:

1
2
private:
std::vector<std::string> list;


The problem occurs when I call addNewElement(std::string newElement) which calls getList(). The program crashes exactly at return list;

I tried to wrap return list; inside
1
2
3
4
5
  try {
      return list;
  } catch (std::exception& ex) {
      std::cout << ex.what();
  }


the program still crashes at return list;

What is going on?
Sep 1, 2016 at 12:36am
Why are you trying to return the vector?

The addNewElement() function has access to the vector so why not just directly access the vector?
Sep 1, 2016 at 12:44am
I'd rather access it through the setter/getter. But even if I will end up accessing the vector directly instead of having the vector returned, I just would like to understand why this happens.
Sep 1, 2016 at 1:22am
I tried to reproduce this error, but couldn't. I think you need to show a complete example which can be compiled and run to show the problem. The cause might be in the part of the code which was not shown.
Sep 1, 2016 at 3:12am
1
2
3
4
void MyList::setList(std::vector<std::string> list)
{
    list = list;
}


Doesn't do what you intend. This is a self-asssignment to a function parameter. (This is why you should mark them `const'.) Disambiguate the name either through the this pointer or rename your parameter.

Sep 1, 2016 at 4:26am
> MyList. it contains a vector
... whatever.

> I tried to wrap return list
you may only catch things that are throw.

> I think you need to show a complete example
I'm sure.


> std::vector<std::string> MyList::getList()
you will return a copy of your member variable.

> if(getList().empty())
¿why is that a special case in an `add_element()' function?
Last edited on Sep 1, 2016 at 4:27am
Topic archived. No new replies allowed.