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?
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;
}
clock() is a proven library function and will not cause a segfault.
You pass a pointer h to initi but there is no storage for h allocated. Then you pass the same pointer to parse. But there still is no storage for the structure!
When you comment clock() out, the call is not made so the stack is not changed. On the stack is also h, an uninitialized local variable.
Related
I'm trying to pause my program for 1 second, and check the system time after that (I'm on Linux)
This is my testing program:
#include <stdio.h>
#include <unistd.h>
#include <time.h>
int main() {
time_t now = time(NULL);
struct tm *time_now = localtime(&now);
printf("now: %d-%d\n", time_now->tm_min, time_now->tm_sec);
int i = 0;
for (; i < 5; i++) {
sleep(1);
}
// This printf result is not as expected
printf("now: %d-%d\n", time_now->tm_min, time_now->tm_sec);
return 0;
}
The expected result is that the second printf would print +5 seconds. Instead, it prints the same time/seconds as the first printf.
I've found (maybe) the same problem posted here, but it doesn't seem to work:
sleep() and time() not functioning as expected inside for loop.
Sorry for my bad english, and thank you for your time.
Code is printing the original *time_now values - as expected.
Simply read time again to use new values.
time_t now = time(NULL);
struct tm *time_now = localtime(&now);
printf("now: %d-%d\n", time_now->tm_min, time_now->tm_sec);
int i = 0;
for (; i < 5; i++) {
sleep(1);
}
// Add
time_t now = time(NULL);
struct tm *time_now = localtime(&now);
printf("now: %d-%d\n", time_now->tm_min, time_now->tm_sec);
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);
}
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.
I was trying to create a timer using gettimeofday. A function "time" has been called for resetting and getting the current time for the timer. But the program is giving garbage values when i tried to get second tine value. Please help
#include<stdio.h>
#include <sys/time.h>
#include <stdlib.h>
struct timeval cur;
double time(int a);
main() {
time(0);
printf("%lf\n",time(1));
sleep(3);
printf("%lf\n",time(1));
}
double time(int a) {
double rtime;
if(a==0) {
gettimeofday(&cur,NULL);
rtime=(double)(cur.tv_sec);
printf("%lf\n",rtime);
} else if(a==1) {
gettimeofday(&cur,NULL);
return((double)(cur.tv_sec-rtime));
}
}
Your routine time() will not remember rtimeunless you
specify rtime as static:
static double rtime;
And: It's unclear why you specify those numbers as doubles.
I am trying to create a function that compare two timestamps, if the first timestamp is earlier than the second one, the function will return -1; if equal, return 0; if later, return 1;
Below is my code, however, it does not work and throws segmentation fault (core dumped) error when I run it:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <string.h>
typedef struct timeval timevalue;
int compare_time_stamps(timevalue *a, timevalue *b)
{
int cmp = timercmp(a, b, >);
if (cmp > 0)
return 1; /* a is greater than b */
else
{
cmp = timercmp(a, b, ==);
if (cmp > 0)
return 0; /* a is equal to b */
else
return -1; /* a is less than b */
}
}
int main()
{
timevalue *start, *end;
gettimeofday(start, NULL);
int i;
for (i = 0; i < 1000000; i++);
gettimeofday(end, NULL);
int cmp = compare_time_stamps(start, end);
printf("comparison result is %d\n", cmp);
return 0;
}
This being said, if I do not start with timevalue *, everything works just fine, see the working code below:
typedef struct timeval timevalue;
int compare_time_stamps(timevalue a, timevalue b)
{
int cmp = timercmp(&a, &b, >);
if (cmp > 0)
return 1; /* a is greater than b */
else
{
cmp = timercmp(&a, &b, ==);
if (cmp > 0)
return 0; /* a is equal to b */
else
return -1; /* a is less than b */
}
}
int main()
{
timevalue start, end;
gettimeofday(&start, NULL);
int i;
for (i = 0; i < 1000000; i++);
gettimeofday(&end, NULL);
int cmp = compare_time_stamps(start, end);
printf("the comparison result is %d\n", cmp);
return 0;
}
What makes the difference between these two approaches? thanks
timevalue start, end;
when you do this, you are allocating space for the struct timeval, which you have called
typedef struct timeval timevalue;
so you are actually allocating the space for the two structures in you current stack frame.
when you do timevalue *start, *end; you are only allocating two pointers to the struct timeval but no memory has been allocated to the struct timeval you would have to use malloc and allocate space.
start = malloc(sizeof(timevalue));
end = malloc(sizeof(timevalue));
also at the end of the function you have to free the malloced memory
printf("comparison result is %d\n", cmp);
free(start);
free(end);
return 0;
}
in C when you define a pointer(int *a) its your job to make sure it points to valid memory. some reading up on pointers should do.
When you use timevalue*, start is a pointer with no memory allocated to it. It will be having garbage value. Hence you get a segmentation fault.
When you use timevalue, the memory is allocated to the start variable and the time value is stored there.
the macro timbal is a struct like this:
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
so you need to allocate memory when you use "*".
I want to get current time (without a current date) in C. The main problem is when I want to do it with functions. When I dont use them, evertyhing is just fine. Can anybody tell me, why my code shows only an hour? (take a look at the attached image). Thanks in advance.
#include <stdio.h>
#include <time.h>
#include <string.h>
char* get_time_string()
{
struct tm *tm;
time_t t;
char *str_time = (char *) malloc(100*sizeof(char));
t = time(NULL);
tm = localtime(&t);
strftime(str_time, sizeof(str_time), "%H:%M:%S", tm);
return str_time;
}
int main(int argc, char **argv)
{
char *t = get_time_string();
printf("%s\n", t);
return 0;
}
sizeof(str_time) gives you the size of char*. You want the size of the buffer str_time points to instead. Try
strftime(str_time, 100, "%H:%M:%S", tm);
// ^ size of buffer allocated for str_time
Other minor points - you should include <stdlib.h> to pick up a definition of malloc and should free(t) after printing its content in main.
The sizeof operator returns the length of the variable str_time which is a pointer to char. It doesn't returns the length of your dynamic array.
Replace sizeof(str_time) by 100 and it will go fine.
try this...
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
Use This Concept Getting System Time and Updating it. I have used this in my project many years before. you can change it as per your requirements.
updtime() /* FUNCTION FOR UPDATION OF TIME */
{
struct time tt;
char str[3];
gettime(&tt);
itoa(tt.ti_hour,str,10);
setfillstyle(1,7);
bar(getmaxx()-70,getmaxy()-18,getmaxx()-30,getmaxy()-10);
setcolor(0);
outtextxy(getmaxx()-70,getmaxy()-18,str);
outtextxy(getmaxx()-55,getmaxy()-18,":");
itoa(tt.ti_min,str,10);
outtextxy(getmaxx()-45,getmaxy()-18,str);
return(0);
}
The previous function will update time whenever you will call it like
and this will give you time
int temp;
struct time tt;
gettime(&tt); /*Get current time*/
temp = tt.ti_min;
If you want to update time the you can use the following code.
gettime(&tt);
if(tt.ti_min != temp) /*Check for any time update */
{
temp = tt.ti_min;
updtime();
}
This is complex code but if you understand it then it will solve your all problems.
Enjoy :)
In getting the time, you can try this one:
#include <stdio.h>
int main(void)
{
printf("Time: %s\n", __TIME__);
return 0;
}
Result:
Time: 10:49:49