c++ - What can I do with an unsigned char* when I needed a string? -
suppose have unsigned char*, let's call it: some_data
unsigned char* some_data;
and some_data has url-like data in it. example:
"aasdasdassdfasdfasdf&foo=cow&asdfasasdfadsfdsafasd"
i have function can grab value of 'foo' follows:
// looks value of 'foo' bool grabfoovalue(const std::string& p_string, std::string& p_foo_value) { size_t start = p_string.find("foo="), end; if(start == std::string::npos) return false; start += 4; end = p_string.find_first_of("& ", start); p_foo_value = p_string.substr(start, end - start); return true; }
the trouble need string pass function, or @ least char* (which can converted string no problem).
i can solve problem casting:
reinterpret_cast<char *>(some_data)
and pass function okie-dokie
...
until used valgrind , found out can lead subtle memory leak.
conditional jump or move depends on uninitialised value(s) __gi_strlen
from gathered, has reinterpret casting messing null indicating end of string. when c++ tries figure out length of string thing's screwy.
given can't change fact some_data represented unsigned char*, there way go using grabfoovalue function without having these subtle problems?
i'd prefer keep value-finding function have, unless there better way rip foo-value out of (sometimes large) unsigned char*.
and despite unsigned char* some_data 's varying, , large size, can assume value of 'foo' somewhere on, thoughts try , char* of first x characters of unsigned char*. potentially rid of string-length issue having me set char* ends.
i tried using combination of strncpy , casting far no dice. thoughts?
you need know length of data unsigned char * points to, since isn't 0-terminated.
then, use e.g:
std::string s((char *) some_data, (char *) some_data + len);
Comments
Post a Comment