vendredi 1 juillet 2016

crash connected to passing std::array by reference


I wrote a program that makes use of standard arrays passed by reference. This is a sample of the code:

#include <iostream>
#include <array>

#define N 4

void f1(std::array<int, N>& x);
void f2(std::array<int, N>& x);

int main()
{
    std::array<int, N> x;

    f1(x);
}

void f1(std::array<int, N>& x)
{
    f2(x);
}

void f2(std::array<int, N>& x)
{
    std::cout << x.size() << std::endl; //is 4
    x[0] = 0;
}

The program compiles correctly, but at execution it crashes at the second line of f2.

If I change the value of N to 3 the program doesn't crash (!).

If I change f1 to use a parameter by value it doesn't crash.

The program worked fine half an hour ago, I changed some parameters in f1 (other arrays that were passed by reference are now passed by value), but I wouldn't know how this may even create a problem.


Aucun commentaire:

Enregistrer un commentaire