Search code examples
c++bus-error

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. What caused this bus error and how can I solve this? Moreover, what is the reason for this strange behaviour?


Solution

  • The temp buffer must be 3 chars in length as sprintf() will append a null terminator after the two hex characters:

    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():

    temp.append(temp1, 2);
    

    An alternative is to avoid using sprintf() and use a std::ostringstream with the IO manipulators:

    #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.