Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault on time(0);

I'm rewriting an old program to do some new stuff, and suddenly I get a segmentation fault error on the following line of code:

time_t seconds_since_time_begun = time(0);

Why, oh why?

Update:
I have included the time.h header file in my code, and when I tried what pmg suggested below, both variables were 4 in size.

When I tried the following:

printf("4\n");
// time_t seconds_since_time_begun = time(0);
printf("5\n");

I still get segmentation fault right after "4" has been printed, even when the line where time() is called is commented out. "5" is not outputted. How is this possible?

Update 2:
I rebuilt my function step by step to try to isolate where the error occurred in my code, and I think I found the problem. I'm not sure what was wrong but it had something to do with a comparison between an integer array value and 0. So, I don't think the segfault was caused by my call to time(0) .. but I'm still not sure what actually happened. Anyways, problem solved. Thanks guys.

like image 762
o01 Avatar asked Dec 22 '22 07:12

o01


2 Answers

Perhaps you have an absurdly large object in your stack frame that's overflowing the stack? See this blog post for a detailed example of how that can occur and an analysis of the situation. The time(2) function allows NULL to be passed to it, and it's highly unlikely your time() implementation has a bug.

like image 88
Adam Rosenfield Avatar answered Jan 09 '23 02:01

Adam Rosenfield


If you have #include <time.h> the compiler knows that it needs to convert that 0 to a NULL pointer. Otherwise, it passes an int to the function.

I think your implementation treats (int)0 differently than (time_t*)0.

So ... add

#include <time.h>

to your code

Edit

Try this

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

int main(void) {
    printf("size of (int): %d\n", (int)sizeof (int));
    printf("size of (time_t*): %d\n", (int)sizeof (time_t*));
    return 0;
}
like image 26
pmg Avatar answered Jan 09 '23 03:01

pmg