-1

Today I encountered some behavior which I don't understand.

I am executing this line:

printf("%s to %s", DateToString(earliestDate), DateToString(latestDate));

With the DateToString, which basically just parses a date struct to a uniformed date string in european date format, looking like this (I think you can ignore most of it. There is a bunch of cases, which I had to handle due to the way I am receiving the dates):

char* DateToString(date_t* _ptr) {
    char output[BUFSIZ] = "00.00.0000";
    char workspace[BUFSIZ];
    _itoa_s(_ptr->day,  workspace, _countof(workspace), 10);
    if(workspace[1] == '\0')
        output[1] = workspace[0];
    else {
        output[0] = workspace[0];
        output[1] = workspace[1];
    }
    output[2] = '.';
    _itoa_s(_ptr->month, workspace, _countof(workspace), 10);
    if (workspace[1] == '\0') {
        output[4] = workspace[0];
    }
    else {
        output[3] = workspace[0];
        output[4] = workspace[1];
    }
    output[5] = '.';
    _itoa_s(_ptr->year, workspace, _countof(workspace), 10);
    if (workspace[0] != '\0')
        output[6] = workspace[0];
    if (workspace[1] != '\0')
        output[7] = workspace[1];
    if (workspace[2] != '\0')
        output[8] = workspace[2];
    if (workspace[3] != '\0')
        output[9] = workspace[3];
    output[10] = '\0';
    return output;
}

With the date_t struct being:

typedef struct date {
    int day;
    int month;
    int year;
}date_t;

When debugging the execution of the DateToString functions within the printf the ouputs in the debugger from VS are:

0x000... "10.05.2022" for the latestDate variable and
0x000... "04.05.2022" for the earliestDate variable.

and the output from the printf is:

04.05.2022 to 04.05.2022

While executing:

printf("%s to ", DateToString(earliestDate));
printf("%s", DateToString(latestDate));

Will give me this output:

04.05.2022 to 10.05.2022

Is this happening due to the fact that I am using a char array which is way too big in the DateToString function or what is the reason this is happening ?

seppel
  • 9
  • 2
  • 2
    @seppel Your code has undefined behavior because you are returning a local array that will not be alive after exiting the function – Vlad from Moscow May 10 '22 at 10:48
  • @VladfromMoscow Can you explain why this behavior is happening exactly ? Is it due to the fact that I am accessing some address that I am not supposed to or is it because printf is using the same value along all arguments in it because I am using the local array or what is the reason ? That is what I want to know. – seppel May 10 '22 at 11:17
  • @seppel After exiting the function the local array is not alive. Its memory can be overwritten. – Vlad from Moscow May 10 '22 at 11:27

0 Answers0