I tried to port the following C++ sorting function to C but now my embedded system goes into hard fault error while trying to sort with my new C function. The function is called roughly once every second and interestingly the first loop the sorting works, it always crashes during the second iteration.
C++ Code:
typedef struct featureData {
float Value[NO_OF_ATT];
float Distance;
bool operator < (const featureData& rhs) const {
return Distance < rhs.Distance;
}
} featureData;
std::sort(trainData, trainData+NO_OF_TRAINDATA);
C Code:
int compare_function(const void *a,const void *b)
{
featureData *x = (featureData *) a;
featureData *y = (featureData *) b;
if ( x->Distance > y->Distance ) return 1;
if ( x->Distance < y->Distance ) return -1;
return 0;
}
qsort(trainData, NO_OF_TRAINDATA, sizeof(*trainData), compare_function);
Further information:
NO_OF_TRAINDATA = 609
NO_OF_ATT = 22
If I set the NO_OF_TRAINDATA to less than 50 the C function runs without any problems. This makes me believe that it's some memory size problem as I frequently run into memory problems on my embedded system. But does the C quicksort (Or whatever is used by calling qsort) work differently than the std::sort in terms of memory allocation?