vector empty() segmentation fault

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?
Why are you trying to return the vector?

The addNewElement() function has access to the vector so why not just directly access the vector?
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.
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.
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.

> 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
Topic archived. No new replies allowed.