Gaurav Arora
Gaurav Arora
Published in
2 min readJun 1, 2016

--

[CPP] Mysterious case of vector.back()

Recently, i got stuck with a case where in one of my code for Table Extraction from Image and Pdf code was getting exception when i was trying to access a valid location in vector.

Guess the Easiest solution ?

Comment the code out!!!

To my amazement code worked after commenting it out!!!! and i was like wow one less thing to debug in already messy code(Table Extraction code is always messy, where you put heuristics)

But your past always catches up with you ;) → To be fully satisfied that, code wasn’t getting broken anywhere else, i had to debug it months later.

I ended up using gdb to find the exact location where code was failing. Code failed when i inserted something in the vector.

What was happening was that gives us exception

I was passing last element of vector as reference to the function and the vector itself.

Reference to the vector was working fine most of the time, But it would start misbehaving when i inserting something new in the vector

Why will the reference of vector given from vector.back go bad ????????????

Because vector gives us the reference to the last element in vector. When we insert new element in the vector, the reference which was taken earlier became bad.

Return valueA reference to the last element in the vector.If the vector object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference.Member types reference and const_reference are the reference types to the elements of the vector (see member types).

Why the last reference will get bad ??

I am not sure :( maybe some implementation issue.

Example

// vector::back
#include <iostream>
#include <vector>
using namespace std;
void func(std::vector<int> & vec, int & did) {
std::cout<<did<<”first did”<<endl;
vec.push_back(229);
std::cout<<did<<”firfkjst did”<<endl;
}
int main ()
{
std::vector<int> myvector;
myvector.push_back(10);
func(myvector, myvector.back());
return 0;
}

Expected Output

10first did
10firfkjst did

True Output

10first did
0firfkjst did

Lesson:

Always debug to narrow the cases which can result in failure(use GDB) and then write a sample program to confirm the behaviour.

Link to a earlier version of TableExtraction for Code https://github.com/samuelharden/TableExtrac

--

--

Gaurav Arora
Gaurav Arora

Currently helping build Zyft.com. Passionate about running, building stuff.