当我使用 sprintf 将大小为 3 的字符串和一个字符输出为大小为 5 的字符串时,出现分段错误(核心转储)

When I use sprintf to output a string of size 3 and a character to a string of size 5, I get a segmentation fault (core dump)

我更改了指向数组的指针,或者分配了更多内存,但都无济于事。

我看了其他的问题,还是解决不了我的问题。

下面是我写的代码(在ubuntu中使用9.3.0 gcc):

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

int main() {
    char* str1 = malloc(5);
    char* str2 = "666";
    sprintf("%s%c", str1, str2, '6');
}

您混淆了 sprintf 参数的顺序。格式字符串是第二个,目标缓冲区是第一个。

参数的顺序应该是这样的

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

int main() {
    char* str1 =(char*) malloc(5);
    char* str2 = "666";
    sprintf(str1,"%s%c",str2,'6');
}