views:

717

answers:

5

What is the correct C++ way of comparing a memory buffer with a constant string - strcmp(buf, "sometext") ? I want to avoid unnecessary memory copying as the result of creating temporary std::string objects.

Thanks.

+1  A: 

strcmp works fine, no copy is made. Alternatively, you could also use memcmp. However, when in C++, why not use std::strings?

Konrad Rudolph
If I convert buf to std::string buffer content will be copied into string object - I want to avoid since after comparison I have nothing to do with it.
Jack
strncmp is slightly safer, but you have to make sure to put the correct value in for 'n'. Alternately, if you know that the buffer is longer than the constant string you are comparing to, then strcmp is fine.
Michael Kohne
+1  A: 

I would use memcmp, and as the last parameter, use the minimum of the 2 sizes of data.

Also check to make sure those 2 sizes are the same, or else you are simply comparing the prefix of the shortest one.

Brian R. Bondy
His data isn't in a string yet - he's trying to avoid putting it in one.
Michael Kohne
Thanks, fixed it.
Brian R. Bondy
A: 

You may do it like,

const char* const CONST_STRING = "sometext";

strcmp(buf,CONST_STRING);
Canopus
From the all answers above I understand that C++/STL has no tools to make such a comparison and one must use simple C approach?
Jack
What comparison? Please post some actual code!
anon
+4  A: 

strcmp is good if you know the contents of your buffer. strncmp might give you a little more security against buffer overflows.

schnaader
+3  A: 

If you're just checking for equality, you may be able to use std::equal

#include <algorithms>

const char* text = "sometext";
const int len = 8; // length of text

if (std::equal(text, text+len, buf)) ...

of course this will need additional logic if your buffer can be smaller than the text

Ferruccio