Reputation: 641
I'm having a segmentation fault error, and I'm not sure why: I have this code: entierlong.h
const int MAXCHIFFRES = 1000;
typedef int tabEnt[MAXCHIFFRES];
struct EntierLong
{
bool Negatif;
tabEnt Chiffres;
};
EntierLong addition(EntierLong n1, EntierLong n2)
{
int retenue,somme,i;
n3 = Convertir(0);
if (n1.Negatif != n2.Negatif)
{
cout<<"Les entierslongs doivent être de même signe.\n";
return(n3);
}
n3.Negatif = n1.Negatif;
retenue = 0;
for(i=0;i<=MAXCHIFFRES-1;i++)
{
somme = n1.Chiffres[i]+n2.Chiffres[i]+retenue;
retenue = int(somme>=10);
n3.Chiffres[i]=somme-retenue*10;
}
return(n3);
}
EntierLong Un_2=Convertir(0), Un_1=Convertir(1), Un=Convertir(0);
EntierLong fibonnaci(int n)
{
int i=0;
switch(n)
{
case 0:
return(Un_2);
break;
case 1:
return(Un_1);
break;
}
for(i=2;i<=n;i++)
{
Un=addition(Un_2,Un_1);
Un_2 = Un_1;
Un_1 = Un;
}
return(Un);
}
Basically I'm storing integer in an array of integer to compute large fibonnaci numbers
everything works fine until I increase MAXCHIFFRES
above 1000
It gives me Segmentation fault: 11
As I understand it, my heap is overflowed at some point
I've tried putting the definitions outside the functions to remove this problem to no avail.
What I don't understand is that summing two EntierLong
togethers works with my function.
I'm very new to cpp, so please let me know if my question is asked improperly
Thanks in advance
Upvotes: 0
Views: 290
Reputation: 3333
If you have memory allocation issues you can replace your EntierLong
type by
struct EntierLong
{
bool Negatif;
std::vector<int> Chiffres;
EntierLong()
{
Chiffres.resize(MAXCHIFFRES,0);
}
};
The constructor will allocate Chiffres
array on the heap.
Upvotes: 2