So I'm trying to make a function that will calculate a
Primitive Root in C, and this is it:
CODE
int PrimitiveRoot(int iPrime)
{
// Calculate Congugates
bool* bCongugates = (bool*) malloc(iPrime*sizeof(bool));
for(int i=0;i<iPrime;i++) bCongugates[i] = true;
for(int i=2;i<iPrime/2;i++)
if(!(iPrime % i))
for(int j=0;j<iPrime;j++)
if(!(j % i))
bCongugates[j] = false;
// Calculate Primitive Roots
bool* bPrimitiveRoots = (bool*) malloc(iPrime*sizeof(bool));
for(int i=0;i<iPrime;i++) bPrimitiveRoots[i] = false;
for(int i=2;i<iPrime;i++)
{
bool* bCongugateTest = (bool*) malloc(iPrime*sizeof(bool));
for(int j=0;j<iPrime;j++) bCongugateTest[j] = false;
for(int j=2;j<iPrime;j++)
bCongugateTest[i^j%iPrime] = true;
bool bRoot = true;
for(int j=2;j<iPrime;j++)
if(bCongugateTest[j] != bCongugates[j])
{
bRoot = false;
break;
}
if(bRoot) bPrimitiveRoots[i] = true;
free(bCongugateTest);
}
// Pick a Root
int iRootCnt = 0;
for(int i=2;i<iPrime;i++)
if(bPrimitiveRoots[i] == true)
iRootCnt++;
int* iPrimitiveRoots = (int*) malloc(iRootCnt*sizeof(int));
iRootCnt = 0;
for(int i=2;i<iPrime;i++)
if(bPrimitiveRoots[i] == true)
{
iPrimitiveRoots[iRootCnt] = i;
iRootCnt++;
}
int iPrimitiveRoot = iPrimitiveRoots[rand() % (iRootCnt+1)];
// Cleanup and Return
free(bCongugates);
free(bPrimitiveRoots);
free(iPrimitiveRoots);
return iPrimitiveRoot;
}
Except it randomly crashes throughout the code

, can anybody see why?