The problem with strcmp is that sometimes, if by mistake, arguments that are passed are not valid C-strings (meaning that p1 or p2 is not terminated with a null character i.e. not NULL-terminated String), then, strcmp continues comparing until it reaches non-accessible memory and crashes or sometimes results to an unexpected behaviour.

Using strncmp you can limit the search, so that it doesn't reach non-accessible memory.

But, from that, it should not be concluded that strcmp is insecure to use. Both the functions work well in the way they are intended to work. Programmer should read man page for that function before using it and must be sincere enough while passing parameters to such library functions.

You can also read THIS which contains an almost similar question.

Answer from Surajeet Bharati on Stack Overflow
Top answer
1 of 8
28

The problem with strcmp is that sometimes, if by mistake, arguments that are passed are not valid C-strings (meaning that p1 or p2 is not terminated with a null character i.e. not NULL-terminated String), then, strcmp continues comparing until it reaches non-accessible memory and crashes or sometimes results to an unexpected behaviour.

Using strncmp you can limit the search, so that it doesn't reach non-accessible memory.

But, from that, it should not be concluded that strcmp is insecure to use. Both the functions work well in the way they are intended to work. Programmer should read man page for that function before using it and must be sincere enough while passing parameters to such library functions.

You can also read THIS which contains an almost similar question.

2 of 8
22

strncmp does not have "advantages over strcmp"; rather they solve different problems. strcmp is for determining if two strings are equal (and if not, possibly how to order/sort them with respect to each other). strncmp is (mainly) for determining whether a string begins with a particular prefix. For example:

if (strncmp(str, "--option=", 9)==0)

will determine if str begins with "--option=". This cannot be achieved by strcmp without either modifying the string to be checked (which may not be a valid operation) or making a useless copy of it. It also cannot be achieved with memcmp unless you already know str points to an object at least 9 bytes in length; otherwise the call to memcmp would have undefined behavior.

There are other usage cases for strncmp too, such as working with non-C-string data.

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ difference-between-strncmp-and-strcmp-in-c-cplusplus
Difference between strncmp() and strcmp() in C/C++
April 14, 2025 - The strcmp() compares two strings till the null character is found, whereas strncmp() only compares a specified number of characters.
Discussions

Is strcmp in embedded C safe? If not, what are the usual substitutes?
In your code, you have inputCmd as an array of pointers, which is not what you want. Anyway, ignoring that, strncmp is the "safer" alternative to strcmp. More on reddit.com
๐ŸŒ r/embedded
17
9
February 3, 2023
Fast String comparisons in C
The problem with the cast is that the pointers might be unaligned, potentially causing slowdowns or even crashes in the worst case when dereferenced. To fix that you need to check the alignment of both pointers at entry and work with the largest possible blocks whose alignment requirements match the least aligned string. Other than that, if I recall correctly the C standard allows casting between any pointer type and char or void pointers, so if you implement the aforementioned fix you should be fine. As for the performance of the code, heavily optimized strncmp implementations use compiler intrinsics that produce SIMD instructions. For example on a modern x86-64 CPU with AVX512 you can check whether two properly aligned 64 8-bit blocks are equal with a single instruction. More on reddit.com
๐ŸŒ r/learnprogramming
17
7
October 29, 2023
This is a super noob question, but strcmp returns 0 if the strings are equal and "truthy" if they are not equal, like if(-1) is true? Is there a different way to compare strings or do I just need to wrap my head around this?
strcmp returns 0 => the strings are equal 1 => the first string is "after" the second when sorted -1 => the first string is "before" the second when sorted It's not really a function to tell you if 2 strings are equal, it's to tell you which "order" the 2 strings are in. It just coincidentally is usable to tell you if 2 strings are equal, because if they are it returns 0 Anything non-zero means the strings aren't equal More on reddit.com
๐ŸŒ r/C_Programming
28
9
October 16, 2023
Confused with strcmp() function.
when we can use it (almost) never. We have std::string. More on reddit.com
๐ŸŒ r/cpp_questions
15
8
September 28, 2021
๐ŸŒ
Quora
quora.com โ€บ Is-Strcmp-safe
Is Strcmp safe? - Quora
Answer: If you are passing strings to strcmp() that are not null terminated you have already lost. The fact that you have a string that is not null terminated (but should be) indicates that you have deeper issues in your code. You cannot change strcmp() to safely deal with this problem. You shou...
๐ŸŒ
Substack
softwarebits.substack.com โ€บ p โ€บ strcmp-vs-strncmp
strcmp vs strncmp - by Taras Tsugrii
October 21, 2023 - In C string comparisons can be peformed using strcmp ยท Code snippet above from glibc library does exactly what weโ€™d expect - looks for the first pair of characters that are different and returns their difference. Obviously this code assumes that passed strings are null-terminated and its behavior is undefined otherwise. Oftentimes, at least one of the strings is known at compile-time, so we can bound the number of traversed charecters. strncmp accepts a third argument that indicates the maximum number of characters that are used for comparison.
๐ŸŒ
Reddit
reddit.com โ€บ r/embedded โ€บ is strcmp in embedded c safe? if not, what are the usual substitutes?
r/embedded on Reddit: Is strcmp in embedded C safe? If not, what are the usual substitutes?
February 3, 2023 -

I have an STM32756-EVAL board, and I would like to compare a uint8_t array to a char array.

uint8_t* inputCmd[5];
code_that_defines_the_inputCmd();
if (strcmp(inputCmd, "FIRMV") == 0){
	do_something();
    }
else{
	do_something_else();
}

Is strcmp in embedded C safe? If not, what are the usual substitutes?

Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c++ โ€บ difference-strncmp-strcmp-c-cpp
Difference between strncmp() and strcmp in C/C++ - GeeksforGeeks
November 10, 2022 - Problem with strcmp function is ... of characters continues till the system crashes. But with strncmp function we can limit the comparison with num parameter....
๐ŸŒ
Ubuntu Manpages
manpages.ubuntu.com โ€บ manpages โ€บ jammy โ€บ man3 โ€บ strcmp.3.html
Ubuntu Manpage: strcmp, strncmp - compare two strings
s2. The locale is not taken into account (for a locale-aware comparison, see strcoll(3)). The comparison is done using unsigned characters. strcmp() returns an integer indicating the result of the comparison, as follows: โ€ข 0, if the
๐ŸŒ
Quora
quora.com โ€บ How-can-strcmp-be-used-to-determine-if-two-strings-are-equal-or-not
How can strcmp be used to determine if two strings are equal or not? - Quora
Answer: Why donโ€™t you look at the specification of the C/C++ libraries? It writes there that the function strcmp returns a negative integer if its first argument is (alphabetically) less than the second, 0 if its arguments are equal, and a positive integer if its first argument is (alphabetically...
๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ php_syntax.asp
W3Schools.com
addcslashes() addslashes() bin2hex() chop() chr() chunk_split() convert_cyr_string() convert_uudecode() convert_uuencode() count_chars() crc32() crypt() echo() explode() fprint() get_html_translation_table() hebrev() hebrevc() hex2bin() html_entity_decode() htmlentities() htmlspecialchars_decode() htmlspecialchars() implode() join() lcfirst() levenshtein() localeconv() ltrim() md5() md5_file() metaphone() money_format() nl_langinfo() nl2br() number_format() ord() parse_str() print() printf() quoted_printable_decode() quoted_printable_encode() quotemeta() rtrim() setlocale() sha1() sha1_file()
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c++ โ€บ stdstrncmp-in-c
std::strncmp() in C++ - GeeksforGeeks
July 2, 2024 - When the strings are not equal, the value returned by the strncmp() function is the difference between the ASCII values of the first unmatched character in str1 and str2.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ fast string comparisons in c
r/learnprogramming on Reddit: Fast String comparisons in C
October 29, 2023 -

Hi, I'm working just for fun on a fast comparison for strings written in C, with the intent of being faster than the normal strncmp function, which is currently the code bellow

```
int fast_strncmp(const char *str1, const char *str2, int len) {
    const char *final_pos = (str1 + len) - 4;
    while (str1 < final_pos) {
        // if characters differ, or end of the second string is reached
        if (*((uint32_t *)str1) != *((uint32_t *)str2)) {
            break;
        }
        // move to the block of characters
        str1 += 4;
        str2 += 4;
    }
    final_pos += 4;
    while (str1 < final_pos) {
        if (*str1 != *str2 || *str1 == 0 || *str2 == 0) {
            return *str1 - *str2;
        }
        // move to the next pair of characters
        str1++;
        str2++;
    }
    return 0;
}
```

Is there any clear problem with the code that could make it a bad option for fast string comparisons. When I wrote it a couple of weeks ago, I didn't think there could be any problem with it, but this week I was watching a couple of videos about C programming and it was mentioned that casting an array of 4 uint8_t to a uint32_t could be a problem. I'm even using this function at work and haven't had a single problem or warning, but since I'm planning to make a youtube video about it, I want to guarantee that my code won't be a problem for other people.

On top of that I've made a couple of benchmarks on the performance to be sure it really is fast, so I've compared it to strncmp and an implementation by https://github.com/mgronhol, that I found here: https://mgronhol.github.io/fast-strcmp/, which got me the following results:

EDIT: reddit was not cooperating with me posting the results text in a well formatted way, so here's the link to the file:

https://github.com/BenjamimKrug/fast_string_comparison/blob/main/results.txt

As you can see, running on the STM32 and the ESP32, my algorithm runs faster by a little compared to the fast_compare function by mgronhol, but running on my PC, it's performing terribly. Does anyone know why that is?

You can find more info about the code in my github repository where I put everything related to this test: https://github.com/BenjamimKrug/fast_string_comparison

P.S.: Sorry if this is the wrong subreddit for this kind of thing, I was going to post it on r/programming, but after reading the rules, I saw that maybe it was best to post it here.

EDIT: fixed code formatting

๐ŸŒ
Quora
quora.com โ€บ What-is-an-effective-alternative-to-strcmp-in-C++-to-compare-strings
What is an effective alternative to strcmp in C++, to compare strings? - Quora
Answer: since C++, since 1998, HAS strings (and are named [code ]std::string[/code]), it make no sense -in 2017- asking about C-string and C library functions. std::basic_string - cppreference.com Comparing strings can be done by comparison operators ([code ] [/code]) or by means ...
๐ŸŒ
Cppreference
en.cppreference.com โ€บ w โ€บ cpp โ€บ string โ€บ byte โ€บ strcmp.html
std::strcmp - cppreference.com
October 13, 2023 - Compares two null-terminated byte strings lexicographically ยท The sign of the result is the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char) that differ in the strings being compared
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 2052055 โ€บ difference-between-strcmp-and-strncmp
Difference between strcmp() and strncmp(). | Sololearn: Learn to code for FREE!
With strncmp, you can specify the number of chars up to which you want to compare two strings. ... Coding Wala You have everything explained in the tutorial. Please, read the COMMENTS in the lessons you can find a great examples and explanations. strcmp(str1, str2) - returns 0 when str1 is equal to str2; - less than 0 when str1 < str2; and - greater than 0 when str1 > str2.