'function return 2D vector gives Segmentation Fault

I'm trying to get some data and push them into a 2d vector (schedule) in getting_schedule function. In the function, when it reaches the return statement, raises segmentation fault. I tried resizing the vector but it didn't make a change.

I'm aware that num_of_schedule should not be more than 479 and program raises the error despite of small values for num_of_schedule.

vector<vector<int>> getting_schedule(int &num_of_schedule)
{
    int duration;
    int period_ID;
    int schedule_counter;
    vector <vector<int>> schedule(480, vector<int>(2));
    while (cin >> duration >> period_ID)
    {
        schedule[num_of_schedule][0] = duration;
        schedule[num_of_schedule][1] = period_ID - 1;
        num_of_schedule++;
    }

    return schedule;
}

int main()
{
    vector <vector<int>> input_schedule(480, vector<int>(2));
    int num_of_schedules = 0;

    input_schedule = getting_schedule(num_of_schedules);

    return 0;
}
c++


Solution 1:[1]

You can use C - style arrays for this purpose. But it would be better if you use std::array for this purpose (as said by @WhozCraig) because for C arrays you'll have to specify the array size in the function too. So you can do something as under:

#include <iostream>
#include <array>

const int max_size = 480;

std::array<std::array<int, 2>, max_size> getting_schedule(std::array<std::array<int, 2>, max_size> arr)
{
    int duration;
    int period_ID;

    int i = 0;
    while (std::cin >> duration >> period_ID)
    {
        arr[i][0] = duration;
        arr[i++][1] = period_ID - 1;
    }

    return arr;
}

int main()
{
    std::array<std::array<int, 2>, max_size> input_schedule{};

    input_schedule = getting_schedule(input_schedule);

    return 0;
}

In the code above, I've made a variable max_size. You can set it to whatever you want to change the maximum no of schedules. But if you want to remove the need for max_size, the following code can be used:

#include <iostream>
#include <vector>
#include <array>

std::vector<std::array<int, 2>> getting_schedule(std::vector<std::array<int, 2>> vec)
{
    int duration;
    int period_ID;

    int i = 0;
    while (std::cin >> duration >> period_ID)
    {
        vec[i][0] = duration;
        vec[i++][1] = period_ID - 1;
    }

    return vec;
}

int main()
{
    std::vector<std::array<int, 2>> input_schedule;
    input_schedule.resize(480);

    input_schedule = getting_schedule(input_schedule);

    return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1