What should I do with unsigned char * when I need a string?

Suppose I have an unsigned char *, let's call it: some_data p>

unsigned char* some_data;

And some_data has url-like data. eg:

"aasdASDASsdfasdfasdf&Foo=cow&asdfasasdfadsfdsafasd"

I have a function that can capture 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 problem is that I need a string to pass this function, or at least char * (which can be converted to a string without any problems).

I can solve this problem by casting:

reinterpret_cast<char *>(some_data)

And then pass it to all okie-dokie functions

...

Until I used valgrind and found out that this could lead to a tedious memory leak.

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

From what I put together, this is due to reinterpretation, confusing zero, indicating the end of the line. Thus, when C ++ tries to figure out the length of the string, it turns out dumb.

, , some_data char *, grabFooValue ?

, , foo ( ) unsigned char *.

char * some_data, , , foo - , , char * X char *. , , char *.

strncpy casting, . ?

+3
1

, char *, 0.

, :

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

Source: https://habr.com/ru/post/1793172/


All Articles