Fasna
Fasna

Reputation: 576

Segmentation Fault in Unit test

I tested my C code with the unity function for unit test. It showed the error and a segmentation fault? Is it usual to have a segmentation fault after a unit test failure? or it is something wrong with my code? Because, when I correct the error, it run successfully

time.c

//gets start time and duration in 24 hour format and returns the total of the two in 24 hour clock


int add_time(int starttime, int duration)
{
     int startHour = starttime / 100;
     int startMinute = starttime % 100;
     int durationHour = duration / 100;
     int durationMinute = duration % 100;

     int finishHour = startHour + durationHour;
     int finishMinute = startMinute + durationMinute;

     if(finishMinute > 59)
     {
         finishMinute %= 60;
        finishHour++; 
    }

     finishHour %= 24;

     return (finishHour * 100 + finishMinute);  
}

//given end and start time, calculates the duration in 24 hour clock (duration is always less than one day) 
int duration(int endtime, int starttime)
{
     if(endtime < starttime)
         endtime += 2400;

     int endHour = endtime / 100;
     int endMinute = endtime % 100;
     int startHour = starttime / 100;
     int startMinute = starttime % 100;

     int durationMinute = endMinute - startMinute;
     int durationHour = endHour - startHour;

     if(durationMinute < 0)
     {
        durationMinute += 60;
        durationHour--;
     }

    return (durationHour * 100 + durationMinute);

}   

testtime.c

#include "unity.h"
#include "time.c"
setUp()
{
}
tearDown()
{
}
void firstTest()
{
    TEST_ASSERT_EQUAL_INT(1, add_time(2359, 2));
    TEST_ASSERT_EQUAL_INT(1530, add_time(1215, 315));
    TEST_ASSERT_EQUAL_INT(2215, add_time(2345, 2230));
}

int main()
{
    firstTest();
    return 0;
}

Upvotes: 0

Views: 9075

Answers (2)

Adi Clepcea
Adi Clepcea

Reputation: 46

It seems you are using Unity for testing. Try to make your main method like this:

int main()
{
   UNITY_BEGIN();
    if (TEST_PROTECT()) {
      RUN_TEST(firstTest);
    }
   UNITY_END();
}

Upvotes: 1

Mark E. McDermott
Mark E. McDermott

Reputation: 203

It isn't correct to say that it is usual to have a segfault after a unit test fails. However, it is usual to expect seg-faults and other errors when your code is wrong.

You can't really generalize about a segfault in relation to a particular framework or technique (unit testing in this case). Until you investigate the cause of the error, all you know is that the error happened.

Try running your incorrect code in a debugger and figuring out exactly where the segfault occurred? Is it in your code, or in the unit test framework?

Upvotes: 2

Related Questions