-2

I have my function print_date_time which I want to return the date as a string. I then want to assign that time to a new variable and print it in main. After that, I want to use it in another function.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <windows.h>
#include <time.h>
#include <assert.h>
static char* print_date_time()
{

    time_t t = time(NULL);
    struct tm* tm = localtime(&t);
    char s[64];
    assert(strftime(s, sizeof(s), "%c", tm));
    //printf("TIME TIME: %s\n", s); 
    return s;
}

/****************************************
*
* MAIN FUNCTION
*
****************************************/
int main(int argc, char** argv)
{
    char *date;


    date = print_date_time();
    printf("time is: %s\n",date);


    //assert(strftime(tab, sizeof(tab), "%c", print_date_time()));
    //print_date_time();

    return 0;
}

I expect the current time.

How do I get a string from a function and assign to it?

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Rata
  • 19
  • 6

1 Answers1

0

char s[64] is stack allocated array and you are returning a pointer to this, which is undefined behaviour. Allocate s on heap instead.

int sz = 64 * sizeof(char);
char *s = malloc(sz);
assert(strftime(s, sz, "%c", tm));
Ashwani
  • 1,938
  • 11
  • 15
  • I think there's a reason that the function was declared `static`. Perhaps suggest to use `static char s[64];`? Also, you may want to discourage from using `assert` on an expression that has side-effects. – S.S. Anne Sep 04 '19 at 19:32
  • @JL2210 making a function `static` just restricts its access to the same compilation unit, it is very different from storage class `static`. And `assert` is there to show the context of code changed, it was already there in OP's code. – Ashwani Sep 04 '19 at 22:03
  • Ah right. Forgot about how `static` applies to functions. However, you may add a note about `assert`; this code wouldn't work with `NDEBUG` defined. – S.S. Anne Sep 04 '19 at 22:15
  • Note that `sizeof(char)` is 1 by definition and `int` is not the proper type for sizes; use `size_t` instead. – S.S. Anne Sep 04 '19 at 22:19