1 year ago

#385268

test-img

Makogan

Why does this code malform a reference access to an stl vector?

I have, what I think is a very basic Cpp program:

// tmp.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <set>
#include <iostream>
#include <fstream>
#include <sstream>

#include "viterbi.hpp"

using namespace std;

std::vector<std::vector<size_t>> FindBoundaries()
{
    std::vector<std::vector<size_t>> boundaries = {{1, 2, 3, 5}, {0, 9, 1, 3, 4, 5, 6, 90}, {3, 4, 5, 6, 7, 8, 9}};
    return boundaries;
}

int main()
{
    auto boundaries = FindBoundaries();
    std::cout << boundaries[0].size() << std::endl;
    Viterbi(boundaries[0], boundaries[0]);

    return 1;
}
// viterbi.hpp
#pragma once

#include <functional>

void Viterbi(
    const std::vector<size_t>& observations,
    const std::vector<size_t>& hidden_states);
// viterbi.cpp
#include <algorithm>
#include <map>
#include <iostream>
#include <vector>

std::vector<size_t> Viterbi(
    const std::vector<size_t>& observations,
    const std::vector<size_t>& hidden_states)
{
    std::cout << hidden_states.size() << std::endl;

    return {};
}

As you can see this is a very simple project.

When I compile it with either gcc or clang, I am getting this ouput:

4
9

Which is utterly bizarre, it really should be printing the same number twice, moreover if I inspect the values of hidden_states using gdb I get this:

std::vector of length 9, capacity 9 = {4300736, 4300768, 4300768, 4300784, 4300848, 4300848, 4300864, 4300920, 4300920}

But observations is fine? If I don;t split this code into 2 files and instead keep it in one then the error does not happen anymore.

I am utterly confused.

c++

gcc

clang

undefined-behavior

0 Answers

Your Answer

Accepted video resources