CodersSC
CodersSC

Reputation: 710

C++ Code Possible Issues

Are there any errors in the code below?

#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>


int main()
{
  std::vector<std::string> myVector;

  myVector.push_back("one");
  myVector.push_back("two");
  myVector.push_back("three");
  myVector.push_back("four");
  myVector.push_back("five");

  std::sort(myVector.begin(),myVector.end(),std::less_equal<std::string>());
  std::string& str = myVector.back();

  std::cout << str << std::endl;

  std::vector<std::string>::const_iterator it = myVector.begin();

  myVector.push_back("six");
  myVector.push_back("seven");

  std::cout << *it << std::endl;

  return 0; 
}

I could only see that by assigning the address of the last element of the vector to str it means that if you remove that element then str is empty, and that this can cause un expected behaviour and even run time issues.

Upvotes: 2

Views: 97

Answers (1)

Barry
Barry

Reputation: 303741

Yes there, the problem is this line:

std::cout << *it << std::endl;

That comes after several push_backs. Since vector is resizeable, it is possible that between you saving off your iterator and adding more elements, that the container had to allocate more memory. If it did have to, then your iterator would be pointing to an element that is no longer part of the vector. It may not clearly look like it, but you have [potentially] a dangling pointer.

Also, same with:

std::string& str = myVector.back();

That reference could become invalidated after the push_backs.

Upvotes: 2

Related Questions