下面的一段代码在一个程序中运行良好并且 造成对方总线错误
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/