简体   繁体   中英

C++ Segfault when returning an empty vector containing vector

I'm having some trouble returning an empty vector which I wasn't expecting. Can anybody help explain please!

This is the offending section: - I am aware the returns are the same, its a placeholder for now.

std::vector<std::vector<double> > PerceptronLayer::calculateLayer() {
    std::vector<std::vector<double> > result;

    if (vPerceptrons.size() == 0) {
        return result;
    }

    return result;
}

If however I make sure that the vector has some values, by setting some dummy data, the function returns as I would expect.

    std::vector<double> val;
    val.push_back(1.0);
    result.push_back(val);

GDB output:

Program received signal SIGSEGV, Segmentation fault.
0x000000000040ba60 in std::vector<double, std::allocator<double> >::operator[]     (this=0x0, __n=0)
at /usr/include/c++/4.7/bits/stl_vector.h:751
751       { return *(this->_M_impl._M_start + __n); }

I could protect the function by not allowing it to run on empty data, but I can't help but feel im missing something fundamental here.

Thanks, Joe

Fixed by - See question comments for details.

Originally I had the return from the posted function going to setup a new vector. Which it didn't like.

std::vector<std::vector<double> > results = pl.calculateLayer(); 

If I split this same code out onto two lines it works as expected. I guess the constructor / copy for std::vector didn't like being given this.

std::vector<std::vector<double> > results; 
results = pl.calculateLayer();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM