0

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);
}  
Community
  • 1
  • 1
dr_times
  • 103
  • 5

1 Answers1

1

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.

Andy Schweig
  • 6,597
  • 2
  • 16
  • 22
  • ...meaning `&tr` sends the address of _the pointer itself_ to the function, and trying to treat that as an array is destined for failure. The address of the allocated array is stored in `tr`, so pass `tr`, not `&tr`. – underscore_d Jul 13 '16 at 17:26
  • Thank you, that worked! I use `void *` because I'm experimenting with an open source library and I use its `info_callback` function for my own purposes without editing much. Depending on `msg` I make a decision about what `void *` actually points to and perform some actions. – dr_times Jul 13 '16 at 18:51