I am writing a pretty basic C program to try to better understand how the time library works and to learn more about C. The problem is, I’m getting a segfault when I return 0 at the end of my main function. Here is the text of the program:
#include <stdio.h>
#include <time.h>
main()
{
time_t *now;
time(now);
struct tm *tp = localtime(now);
printf("%s", asctime(tp));
return 0;
}
Using gdb I can see that on line 10 (return 0) everything has gone fine so far, and my only two variables are now and tp. Here is what happens when I print them:
(gdb) print now
$7 = (time_t *) 0x7fff5fbff838
(gdb) print tp
$8 = (struct tm *) 0x7fff7b13e470
(gdb) print *now
$9 = 1345338893
(gdb) print *tp
$10 = {
tm_sec = 53,
tm_min = 14,
tm_hour = 21,
tm_mday = 18,
tm_mon = 7,
tm_year = 112,
tm_wday = 6,
tm_yday = 230,
tm_isdst = 1,
tm_gmtoff = -14400,
tm_zone = 0x100802518 "EDT"
}
Everything seems just fine. But then when I hit n,
Cannot access memory at address 0x50303e0d
0x0000000050303e0d in ?? ()
I don’t understand what could be causing this error. Returning 0 at the end of main has never hurt me before, and the memory address doesn’t match up with either of the ones I’m using. When I run my program in Terminal, I get Segmentation fault: 11.
The only thing I can think of is that it’s something to do with the operating system, which makes sense for several reasons – the relatively low memory address, and the error being thrown by the O.S. trying to access the memory address on the stack to return to. Why could this be happening, though? I don’t know much about Operating Systems (I’m learning about C so I can skip a course requirement and take the Operating Systems course offered by my university) so maybe this is a really easy question. I tried running another C program in the same directory, and it went just fine.
You didn’t initialize
nowor maybe you wanted to initialize it on the stack, like