为什么会出现以下段错误?
我正在使用标准的c99,icc编译器和unix.我不能让这不是段错误,我很好奇为什么.我对strcat/strcpy不太熟悉.
char *first = "First";
char *second = "Second";
char *both = (char *)malloc(strlen(first) + strlen(second) + 2);
strcpy(both, first);
strcat(both, " ");
strcat(both, second);
sprintf("%s %s", first, second);
Run Code Online (Sandbox Code Playgroud)
sprintf("%s %s", first, second);
Run Code Online (Sandbox Code Playgroud)
第一个参数sprintf是目标缓冲区.您已将常量字符串作为目标缓冲区.
如果你只是想打印一些东西,你的意思是printf?
否则,正确使用将是这样的:
// declaration of "dest" left as exercise for the reader
//
sprintf(dest, "%s %s", first, second);
Run Code Online (Sandbox Code Playgroud)
虽然,sprintf已被取代snprintf,但最好避免缓冲区溢出.
| 归档时间: |
|
| 查看次数: |
383 次 |
| 最近记录: |