如何解决此总线错误

How to solve this bus error?

本文关键字:总线 错误 解决 何解决      更新时间:2023-10-16

以下代码在一个程序中运行良好导致另一个出现总线错误

    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]是byte类型,temp是字符串。是什么导致了这个总线错误?我该如何解决这个问题?此外,这种奇怪行为的原因是什么?

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

char temp1[3];

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

temp.append(temp1, 2);

另一种选择是避免使用sprintf(),并将std::ostringstream与IO操纵器一起使用:

#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实例。

一个包含2个字符的字符串实际上需要3个字节,因为在字符串末尾还有一个终止''