如何解决此总线错误
How to solve this 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]是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个字节,因为在字符串末尾还有一个终止' '
。
相关文章:
- 总线错误,堆上分配的内存
- 总线错误 10 - 字符 * 数组
- C/C++ 字符串错误与 ARM SEG 故障总线错误
- 获取总线错误:10 并附加字符串
- 多维矢量总线错误
- 链表的总线错误(核心转储)
- C 结构中的总线错误
- 如何解决此总线错误
- 调用虚拟方法导致总线错误
- 尝试打印数组时出现总线错误和奇怪的输出
- 尝试在共享内存中写入时发生总线错误
- C++ 总线错误:尝试解析和更新字符串时出现 10
- 我在以下代码中收到总线错误
- 总线错误:10 还有更多索引要去
- 使用链表的动态队列//总线错误:10(C++)
- 快速修复程序给出的总线错误
- 总线错误10或分段错误11
- C++ 在类成员"无符号长"上使用"^="和"<<"时出现总线错误
- 析构函数中的模拟总线错误
- 试图获取vector迭代器的值时出现总线错误10