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?
The
tempbuffer must be 3 chars in length assprintf()will append a null terminator after the two hex characters:There appears to be no reason to be using dynamically allocated memory. Note you can avoid the creation of the temporary
stringnamedtemp2by usingstd::string::append():An alternative is to avoid using
sprintf()and use astd::ostringstreamwith the IO manipulators:Then use
s.str()to obtain thestd::stringinstance.