0

I have the following problem I'm trying to print the return of this function and I'm having a segmentation fault and idk why

  char * cfnGetTime()
{
    char * szDate;
    struct tm *ptTime;
    time_t tTimeNow;
    
    /* Get date and time */
    (void)time(&tTimeNow);
    ptTime=localtime(&tTimeNow);
    (void)strftime(szDate, MAXPATHLEN, "%Y%m%d%H%M%S", ptTime);
    
    return szDate;
} 

when I do this

fprintf(gpfdLogFile, "%s%s - Comienza el proceso %s version %s\n", 
            __LINE__, cfnGetTime(), MODULO, LABEL);
  • 5
    `szDate` does not point to any memory location. You can use dynamic memory allocation: `char *szDate = malloc(MAXPATHLEN);` This creates a block of memory `MAXPATHLEN` bytes in size. Don't forget to later `free` that memory. – 001 Feb 17 '21 at 19:30
  • 1
    @Gabriela OhSatan Where does char * szDate point? – Vlad from Moscow Feb 17 '21 at 19:30
  • Why do you print the integer `__LINE__` with "%s"? Did you read the documentation for `fprintf`? – Werner Henze Feb 17 '21 at 19:31
  • Another option is to pass an array to the function and use that: `char * cfnGetTime(char *szDate, size_t length) {...}` and then: `char buffer[MAXPATHLEN]; cfnGetTime(buffer, sizeof(buffer));` This way, there's no need to `free` the memory. – 001 Feb 17 '21 at 19:33
  • yeah you are right __LINE__ printf read it as an integer but why if I defined like this #define __LINE__ "-----------------------------------\n" – Gabriela OhSatan Feb 17 '21 at 19:35
  • Or you could just use the `ctime` function: https://pubs.opengroup.org/onlinepubs/007904875/functions/ctime.html – jwdonahue Feb 17 '21 at 19:37
  • There is a built in macro `__LINE__`. You want to use your macro `LINE`. – 001 Feb 17 '21 at 19:37
  • haaaaaaaaaaa okok interesting thanks! – Gabriela OhSatan Feb 17 '21 at 19:37
  • thank you @jwdonahue I will try to use it! – Gabriela OhSatan Feb 17 '21 at 19:43

0 Answers0