开发者

What can I do with an unsigned char* when I needed a string?

开发者 https://www.devze.com 2023-02-11 04:30 出处:网络
Suppose that I have a unsigned char*, let\'s call it: some_data unsigned char* some_data; And some_data has url-like data in it.for example:

Suppose that I have a unsigned char*, let's call it: some_data

unsigned char* some_data;

And some_data has url-like data in it. for example:

"aa开发者_StackOverflow社区sdASDASsdfasdfasdf&Foo=cow&asdfasasdfadsfdsafasd"

I have a function that can grab the value of 'foo' as follows:

// looks for the 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 is that I need a string to pass to this function, or at least a char* (which can be converted to a string no problem).

I can solve this problem by casting:

reinterpret_cast<char *>(some_data)

And then pass it to the function all okie-dokie

...

Until I used valgrind and found out that this can lead to a subtle memory leak.

Conditional jump or move depends on uninitialised value(s)  __GI_strlen

From what I gathered, it has to do with the reinterpret casting messing up the null indicating the end of the string. Thus when c++ tries to figure out the length of the string thing's get screwy.

Given that I can't change the fact that some_data is represented by an unsigned char*, is there a way to go about using my grabFooValue function without having these subtle problems?

I'd prefer to keep the value-finding function that I already have, unless there is clearly a better way to rip the foo-value out of this (sometimes large) unsigned char*.

And despite the unsigned char* some_data 's varying, and sometimes large size, I can assume that the value of 'foo' will be somewhere early on, so my thoughts were to try and get a char* of the first X characters of the unsigned char*. This could potentially get rid of the string-length issue by having me set where the char* ends.

I tried using a combination of strncpy and casting but so far no dice. Any thoughts?


You need to know the length of the data your unsigned char * points to, since it isn't 0-terminated.

Then, use e.g:

std::string s((char *) some_data, (char *) some_data + len);
0

精彩评论

暂无评论...
验证码 换一张
取 消