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?
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.
yes it is perfectly safe and considered standard practice. String literals are guaranteed to be properly null terminated.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With