cpointerssegmentation-faultvoid-pointerstimeval

Pass void pointer as function parameter and cast it to timeval array


Assume I have a function calc_sum() and I want to measure its execution time. I have a callback function info_callback() which prints a message and calculates execution time, it takes void pointer as parameter. I want to cast void* to struct timeval * to retrieve start/end of execution time and calculate the difference, but I can't understand how to pass the pointer to array struct timeval * so that I can access its elements from within info_callback() function. Whatever I try, I get segmentation fault...

How should I pass and cast pointers to get it work?

EDIT: fixed error in code as Andy Schweig suggested

#include <stdio.h>
#include <sys/time.h>

void calc_sum(int a, int b)
{
    int k = a + b;
    printf("sum = %d\n", k);
}

void info_callback(const char *msg, void *client_data)
{
    struct timeval *t = (struct timeval *) client_data;
    double time = (t[1].tv_sec - t[0].tv_sec) * 1000.0; // !!!SEGMENTATION FAULT!!!
    time += (t[1].tv_usec - t[0].tv_usec) / 1000.0; //

    printf("[TIME] %s: %f, ms", msg, time);
}

int main(int argc, char *argv[])
{
   struct timeval t1, t2;
   gettimeofday(&t1, NULL);

   calc_sum(2, 3);

   gettimeofday(&t2, NULL);

   struct timeval * tr = (struct timeval*) malloc(2 * sizeof(struct timeval));
   tr[0] = t1;
   tr[1] = t2;

   double time = (tr[1].tv_sec - tr[0].tv_sec) * 1000.0; // sec to ms 
   time += (tr[1].tv_usec - tr[0].tv_usec) / 1000.0;   // us to ms

   printf("time = %f, ms\n", time);

   info_callback("Execution time", tr);
   free(tr);
}  

Solution

  • You should pass tr to info_callback instead of &tr. tr points to the array you allocated; &tr is a pointer to the pointer tr.

    By the way, any particular reason for using void * instead of the actual type? If you had used the actual type, the compiler would have flagged this.