Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any safe strcmp?

Tags:

c++

c

strcmp

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?

like image 967
P-P Avatar asked Oct 26 '09 09:10

P-P


People also ask

Is strcmp safe?

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.

Can you use strcmp with a string literal?

yes it is perfectly safe and considered standard practice. String literals are guaranteed to be properly null terminated.

Does strcmp stop at null terminator?

The strcmp() built-in function compares the string pointed to by string1 to the string pointed to by string2 The string arguments to the function must contain a NULL character ( \0 ) marking the end of the string.


1 Answers

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.

like image 84
Wernsey Avatar answered Sep 29 '22 19:09

Wernsey