3

I am just tryng to use sprintf to concatenate some strings but I had this problem, I don't understand why my program is crashing using sprintf in C. Why this code runs?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char* dateTime = malloc(16*sizeof(char));

    printf("Date: %s\n", __DATE__);
    printf("Time: %s\n", __TIME__);

    sprintf (dateTime, "%s, %s\0", __DATE__, __TIME__);

    printf("%s", dateTime);
    free(dateTime);

    return 0;
}

And this one not?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char* dateTime = malloc(16*sizeof(char));

    //printf("Date: %s\n", __DATE__);
    //printf("Time: %s\n", __TIME__);

    sprintf (dateTime, "%s, %s\0", __DATE__, __TIME__);

    printf("%s", dateTime);
    free(dateTime);

    return 0;
}
3
  • check return value of sprintf. Commented Dec 23, 2016 at 22:33
  • Curious, Why 16 in char* dateTime = malloc(16*sizeof(char));? Commented Dec 24, 2016 at 5:10
  • Note that the \0 at the ends of the strings is redundant; the C compiler adds a null byte at the end of a string automatically. Commented Dec 24, 2016 at 5:34

2 Answers 2

7

On my compiler, the string you're creating is 21 characters long (Dec 23 2016, 23:29:57), so you're basically allocating too few bytes for your string.

You get undefined behaviour. So it crashes without the printf statements, and kind of works with them because the computer is not doing the exact same thing, but it's still wrong.

BTW you could achieve what you want safely by just doing this:

const char *dateTime= __DATE__ " " __TIME__;

since __DATE__ and __TIME__ are already string macros. Preprocessor can do the concatenation at compile time.

If you want to compute the numbers of characters needed you could use snprintf with a NULL buffer (c99 only):

Calling snprintf with zero bufsz and null pointer for buffer is useful to determine the necessary buffer size to contain the output:

const char *fmt = "sqrt(2) = %f";
int sz = snprintf(NULL, 0, fmt, sqrt(2));
char buf[sz + 1]; // note +1 for terminating null byte
snprintf(buf, sizeof buf, fmt, sqrt(2));

http://en.cppreference.com/w/c/io/fprintf

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

Comments

4

It appears that your buffer is too small for sprintf:

char* dateTime = malloc(16*sizeof(char));

The __DATE__ and __TIME__ always takes more than 15 bytes (not including NUL character). Writing past the array boundary causes undefined behaviour.

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.