1

I have a string which is a date and comes in the format yyyymmdd. I need to find out the day,month, year and store them in separate strings and use them further. I have written the following code

char *date="20151221";
char day[2];
char month[2];
char year[4];
sprintf(day, "%c%c", date[6], date[7]);
sprintf(month, "%c%c", date[4], date[5]);
sprintf(year, "%c%c%c%c", date[0], date[1],date[2],date[3]);
lr_output_message("day is %s",day);
lr_output_message("month is %s",month);
lr_output_message("year is %s",year);

But the output am getting is

day is 21122015

month is 122015

year is 2015

Maybe its a dumb question,but I am new to C. Can anybody please explain the reason for this?

2
  • 1
    When you use sprintf it will append a null to the end of the string. The problem is that you are overwriting neighboring variables with the nulls. This is undefined behavior. Check out the man page for sprintf. Commented Dec 23, 2015 at 3:24
  • 3
    Did you know that a 2-character string actually contains 3 characters? For example, "ab" is 'a', 'b' and '\0'. Commented Dec 23, 2015 at 3:24

1 Answer 1

1

As per the C11 standard, chapter §7.21.6.6, sprintf() function, (emphasis mine)

The sprintf function is equivalent to fprintf, except that the output is written into an array (specified by the argument s) rather than to a stream. A null character is written at the end of the characters written; [...]

which indicates, in case of

sprintf(day, "%c%c", date[6], date[7]);

day should have a minimum space allocated for 3 chars, including the terminating null to be written. Now, in your case, it does not have the room for the terminating null, and thereby, sprintf() try to write into past the allocated memory region, invoking undefined behavior.

You need to consider the space allocation for the terminating null also while defining the arrays.

Same goes for other arrays, too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.