Jake Jake - 1 month ago 21
C Question

segmentation fault when using clock() function

My following code gives

segmentation fault: 11
only when I add the
clock()
function to calculate the time elapsed (When I comment clock(), I get results with no issues!!! ):

typedef struct heap_strct *Sort;
struct heap_strct {
int count;
int size;
int *queue;
};

int main() {
time_t start = clock();
Sort h; // Sort is a structure
initi(h);
parse(h);
time_t end = clock();
double time_elapsed = (double)(end - start) / CLOCKS_PER_SEC;

printf("Time = %f", time_elapsed);
}


I am using
#include <time.h>
but I don't know why such a fault appears! Kindly, can someone tell me why?

Answer

You pass an uninitialized pointer to function initi(). If this function modifies the structure, you invoke undefined behavior.

It is a very bad habit to hide pointers behind typedefs. The comment is completely misleading: Sort is not a structure!

Define a structure directly and pass its address:

#include <time.h>

struct heap_strct {
    int count;
    int size;
    int *queue;
};

int main(void) {
    clock_t start = clock();
    struct heap_strct h;   // h is a structure for real now!
    initi(&h);
    parse(&h);
    time_t end = clock();
    double time_elapsed = (double)(end - start) / CLOCKS_PER_SEC;

    printf("Time = %f\n", time_elapsed);
    return 0;
}