-3

I am trying to send a time_t to a function by using a time_t pointer variable. I don't get any compiler warnings when compiling my code, but a valgrind error when I run the code with valgrind.

My code:

printTime(time_t *time){
    <prints time>
}
int main(void){
    struct tm beginTime = {0};
    time_t *begin = 0;

    strptime("2012",""%Y,&beginTime);
    beginTime.tm_isdst = -1;
    *begin = mktime(&beginTime);    **<-- Valgrind error points here**

    printTime(begin); 


return 0;
}

This is the valgrind error I am getting:

Invalid write of size 8. (Points at the location pointed at above)
J. Doe
  • 7
  • 1

1 Answers1

0

there are several syntax errors in the posted code.

when compiling, enable all the warnings, then fix those warnings

the following code:

  1. cleanly compiles
  2. runs without crashing

now the code:

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



void printTime(time_t *time)
{
    (void)time;
    //<prints time>
}


int main(void)
{
    struct tm beginTime = {0};
    time_t *begin = 0;

    strptime("2012","%Y",&beginTime);
    beginTime.tm_isdst = -1;
    begin = mktime(&beginTime);    // << notice no '*' before 'begin'
                                   // because 'begin' is already declared as a pointer

    printTime(begin);


return 0;
}

If valgrind continues to indicate a problem, you could try passing begin to free().

I.E. just before the return 0; statement insert:

free( begin );
user3629249
  • 16,402
  • 1
  • 16
  • 17