简体   繁体   English

如何解决此总线错误?

[英]How to solve this bus error?

The following piece of code worked well in one program and caused a bus error in the other 以下代码在一个程序中运行良好,而在另一个程序中导致总线错误

    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] is of type byte and temp is a string. s_ip [b]是字节类型,而temp是字符串。 What caused this bus error and how can I solve this? 是什么导致了此总线错误,我该如何解决? Moreover, what is the reason for this strange behaviour? 此外,这种奇怪行为的原因是什么?

The temp buffer must be 3 chars in length as sprintf() will append a null terminator after the two hex characters: temp缓冲区的长度必须为3个字符,因为sprintf()将在两个十六进制字符后附加一个空终止符:

char temp1[3];

There appears to be no reason to be using dynamically allocated memory. 似乎没有理由使用动态分配的内存。 Note you can avoid the creation of the temporary string named temp2 by using std::string::append() : 注意,可以通过使用std::string::append()避免创建名为temp2的临时string

temp.append(temp1, 2);

An alternative is to avoid using sprintf() and use a std::ostringstream with the IO manipulators: 另一种选择是避免使用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]);
}

Then use s.str() to obtain the std::string instance. 然后使用s.str()获得std::string实例。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM