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;
}
sprintf.16inchar* dateTime = malloc(16*sizeof(char));?\0at the ends of the strings is redundant; the C compiler adds a null byte at the end of a string automatically.