如何解决这个总线错误?

sjs*_*sam 0 c++ bus-error

下面的代码在一个程序中运行良好,并在另一个程序中导致总线错误

    char *temp1;
    temp1=(char*)malloc(2);
    for(b=3;b>=0;b--)
       {
       sprintf(temp1,"%02x",s_ip[b]);
       string temp2(temp1); 
       temp.append(temp2);
       } 
Run Code Online (Sandbox Code Playgroud)

s_ip [b]的类型为byte,temp是一个字符串.导致此总线错误的原因是什么?而且,这种奇怪行为的原因是什么?

hmj*_*mjd 6

所述temp缓冲器的长度必须为3个字符为sprintf()两个十六进制字符之后将追加空终止:

char temp1[3];
Run Code Online (Sandbox Code Playgroud)

似乎没有理由使用动态分配的内存.请注意,您可以使用以下命令来避免创建临时string命名:temp2std::string::append()

temp.append(temp1, 2);
Run Code Online (Sandbox Code Playgroud)

另一种方法是避免在IO操纵器上使用sprintf()和使用std::ostringstream:

#include <sstream>
#include <iomanip>

std::ostringstream s;

s << std::hex << std::setfill('0');

for (b = 3; b >= 0; b--)
{
    s << std::setw(2) << static_cast<int>(s_ip[b]);
}
Run Code Online (Sandbox Code Playgroud)

然后使用s.str()获取std::string实例.