Unfixable
Unfixable

Reputation: 450

Porting array sorting function from c++ to c on embedded system

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?

Upvotes: 2

Views: 456

Answers (1)

Unfixable
Unfixable

Reputation: 450

I found out the problem: I'm running FreeRTOS and mistakenly assumed that a task in freeRTOS is allocating it's stack memory on the system stack. What I mean is that FreeRTOS internal stack is actually allocated on the heap of my device. After increasing the device heap significantly it is running without any problems.

But I wonder about the difference between std::sort and qsort(), one was working with the smaller FreeRTOS stack while the other wasn't. I assume qsort() has a higher memory footprint which led to a stack/heap overflow.

Upvotes: 2

Related Questions