I've been going through the K&R 2nd edition book and I've been stuck trying to get one of the examples to run properly.
The code taken straight from chapter 5 in the book (with some random variables I added in main):
static char daytab[2][13] = {
    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
/* day_of_year: set day of year from month & day */
int day_of_year(int year, int month, int day)
{
    int i, leap;
    leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
    for (i = 1; i < month; i++)
    day += daytab[leap][i];
    return day;
}
/* month_day: set month, day from day of year */
void month_day(int year, int yearday, int *pmonth, int *pday)
{
    int i, leap;
    leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
    for (i = 1; yearday > daytab[leap][i]; i++)
    yearday -= daytab[leap][i];
    *pmonth = i;
    *pday = yearday;
}
int main(){
    int x = 5, y = 10;
    int *q, *p;
    month_day(x, y, q, p);
}
This program was giving me segmentation faults, so I tried running it in gdb.
I put a breakpoint in the month_day function, and something immediately caught my attention.
gdb shows that pmonth is initialized to some address, but pday is initialized to 0x0. This can't be right and I know that, but what is causing this in the first place?
This is the month_day function with its parameters in gdb:
month_day (year=5, yearday=10, pmonth=0x7fffffffe150, pday=0x0) at e5-8.c:19
And as expected, when attempting to print *pmonth, it works as it should, but printing *pday does not because its initialized to 0x0.
gdb output:
19      leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
(gdb) print pday
$1 = (int *) 0x0
(gdb) print *pday
Cannot access memory at address 0x0
(gdb) print *pmonth
$2 = 1
This is most likely an easy fix but I'd like to understand what's going on too!
 
    