Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function returning const char *

I've developed a small helper function for a unit test class, which takes my vector<unsigned char> and converts it back to a const char *. I wrote this so I can pass it to gtest's ASSERT_STREQ macro for simple comparisons. Here it is:

const char * convertVecToChar(std::vector<unsigned char>& source)
{
    std::vector<unsigned char>::size_type size = source.size();
    char* data = (char*)malloc(sizeof(char) * (size + 1)); 
    memcpy(data, &source[0], size);
    data[size] = 0;
    return data;
}

And here's an example of it being called:

ASSERT_STREQ("de", convertVecToChar(somevector));

I presume this is leaky however as I'm calling malloc, but without calling delete further down the road?

Is there a more elegant way to do this, which does not involve creating a separate const char * variable for every time I call ASSERT_STREQ within a test method?

Big thanks in advance for all responses.

Chris

like image 669
Mr Chris Avatar asked Mar 22 '12 09:03

Mr Chris


People also ask

What does char * const mean in C?

char* const says that the pointer can point to a char and value of char pointed by this pointer can be changed. But we cannot change the value of pointer as it is now constant and it cannot point to another char.

Can char * be used as a return type in C?

Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string. All forms are perfectly valid. Note the use of const , because from the function I'm returning a string literal, a string defined in double quotes, which is a constant.

Can a char * be passed as const * argument?

In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...

What is the difference between const char * and char * const?

The difference is that const char * is a pointer to a const char , while char * const is a constant pointer to a char . The first, the value being pointed to can't be changed but the pointer can be. The second, the value being pointed at can change but the pointer can't (similar to a reference).


1 Answers

Return a std::string instead of a char* (malloc(), or new, unrequired):

std::string convertVecToChar(std::vector<unsigned char>& source)
{
    return std::string(source.begin(), source.end());
}

and use:

ASSERT_STREQ("de", convertVecToChar(somevector).c_str());  
like image 171
hmjd Avatar answered Sep 19 '22 16:09

hmjd