Is there any safe strcmp?

P-P picture P-P · Oct 26, 2009 · Viewed 32.6k times · Source

I made a function like this:

bool IsSameString(char* p1, char* p2) 
{
     return 0 == strcmp(p1, p2);
}

The problem is that sometimes, by mistake, arguments are passed which are not strings (meaning that p1 or p2 is not terminated with a null character). Then, strcmp continues comparing until it reaches non-accessible memory and crashes. Is there a safe version of strcmp? Or can I tell whether p1 (and p2) is a string or not in a safe manner?

Answer

Wernsey picture Wernsey · Oct 26, 2009

No, there's no (standard) way to tell whether a char * actually points to valid memory.

In your situation, it is better to use std::string rather than char *s for all your strings, along with the overloaded == operator. If you do this, the compiler would enforce type safety.

EDIT: As per the comments below if you find yourself in a situation where you sometimes pass char *s that may or may not be valid strings to functions that expect null-terminated strings then something is fundamentally wrong with your approach, so basically @janm's answer below.