我只是尝试使用sprintf连接一些字符串,但我有这个问题,我不明白为什么我的程序在C中使用sprintf崩溃.为什么这个代码运行?
#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;
}
Run Code Online (Sandbox Code Playgroud)
这不是吗?
#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;
}
Run Code Online (Sandbox Code Playgroud)
在我的编译器上,你创建的字符串是21个字符长(Dec 23 2016, 23:29:57),所以你基本上为字符串分配了太少的字节.
你得到了未定义的行为.所以它在没有printf语句的情况下崩溃,并且与它们一起工作,因为计算机没有做同样的事情,但它仍然是错误的.
顺便说一句,你可以通过这样做来安全地实现你想要的东西:
const char *dateTime= __DATE__ " " __TIME__;
Run Code Online (Sandbox Code Playgroud)
因为__DATE__并且__TIME__已经是字符串宏.预处理器可以在编译时进行连接.
如果要计算需要的时候可以使用的字符数snprintf有NULL缓冲(C99只):
使用零bufsz和空指针调用snprintf缓冲区对于确定包含输出所需的缓冲区大小很有用:
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));
Run Code Online (Sandbox Code Playgroud)
http://en.cppreference.com/w/c/io/fprintf