c++ - 如何解决这个总线错误?

标签 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);
       } 

s_ip[b]是字节类型,temp是字符串。是什么导致了这个总线错误,我该如何解决? 此外,这种奇怪行为的原因是什么?

最佳答案

temp 缓冲区的长度必须为 3 个字符,因为 sprintf() 将在两个十六进制字符后附加一个空终止符:

char temp1[3];

似乎没有理由使用动态分配的内存。请注意,您可以通过使用 std::string::append() 来避免创建名为 temp2 的临时 string :

temp.append(temp1, 2);

另一种方法是避免使用 sprintf() 并使用带有 IO 操纵器的 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]);
}

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

关于c++ - 如何解决这个总线错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12368098/

相关文章:

c++ - 为什么这种链接方法不起作用?

c++ - 错误 : expected ‘,’ or ‘...’ before ‘&’ token

linux - 在 x86 Linux 上调试 SIGBUS

c - 为什么这个 C 代码给我一个总线错误?

c - 为什么此 C 结构初始化代码会产生总线错误?

c++ - OPERATOR_BRACKET_IS_NOT_SUPPORTED 在 boost::bimap 上

android - OpenCv C++ 裁剪图像

c++ - 如何找出动态分配的多维数组中槽的地址?

c - 总线错误与段错误

crash - 总线错误的可能原因:物理地址不存在