59

I wrote this small piece of code in C to test memcmp() strncmp() strcmp() functions in C.

Here is the code that I wrote:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
        char *word1="apple",*word2="atoms";

        if (strncmp(word1,word2,5)==0)
                printf("strncmp result.\n");
        if (memcmp(word1,word2,5)==0)
                printf("memcmp result.\n");
        if (strcmp(word1,word2)==0)
                printf("strcmp result.\n");
}

Can somebody explain me the differences because I am confused with these three functions?

My main problem is that I have a file in which I tokenize its line of it,the problem is that when I tokenize the word "atoms" in the file I have to stop the process of tokenizing.

I first tried strcmp() but unfortunately when it reached to the point where the word "atoms" were placed in the file it didn't stop and it continued,but when I used either the memcmp() or the strncmp() it stopped and I was happy.

But then I thought,what if there will be a case in which there is one string in which the first 5 letters are a,t,o,m,s and these are being followed by other letters.

Unfortunately,my thoughts were right as I tested it using the above code by initializing word1 to "atomsaaaaa" and word2 to atoms and memcmp() and strncmp() in the if statements returned 0.On the other hand strcmp() it didn't. It seems that I must use strcmp().

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
und3rd06012
  • 717
  • 1
  • 14
  • 19
  • 2
    Kudos for including source code. Now, it would make your question clearer if you showed what results you get, and what results you expected. – Pascal Cuoq Oct 26 '12 at 23:00
  • @PascalCuoq for example if I initialize word1 to "atomr" and word2 to "atoms" the if statement which contains the memcmp() is never true when I run the executable. – und3rd06012 Oct 26 '12 at 23:22
  • @PascalCuoq.Okay I found my answer to the question. – und3rd06012 Oct 27 '12 at 00:02
  • @el10780: No, I meant a manual page. For example, like this — http://www.kernel.org/doc/man-pages/online/pages/man3/memcmp.3.html –  Oct 27 '12 at 00:04
  • yes I have seen these pages,I got confused though.I dot not know maybe I am tired.:)It's 3 a.m here.I wouldn't ask before searching it here and over the Internet. – und3rd06012 Oct 27 '12 at 00:22
  • 2
    It's worth noting that memcmp can be a lot faster since it's usually optimized to use the biggest type supported by a single load and store as soon as one of the addresses is aligned. So it actually compares many characters at once instead of one, possibly 8 character comparisons, probably at least 4. – 2013Asker Dec 28 '13 at 00:45

6 Answers6

131

In short:

  • strcmp compares null-terminated C strings
  • strncmp compares at most N characters of null-terminated C strings
  • memcmp compares binary byte buffers of N bytes

So, if you have these strings:

const char s1[] = "atoms\0\0\0\0";  // extra null bytes at end
const char s2[] = "atoms\0abc";     // embedded null byte
const char s3[] = "atomsaaa";

Then these results hold true:

strcmp(s1, s2) == 0      // strcmp stops at null terminator
strcmp(s1, s3) != 0      // Strings are different
strncmp(s1, s3, 5) == 0  // First 5 characters of strings are the same
memcmp(s1, s3, 5) == 0   // First 5 bytes are the same
strncmp(s1, s2, 8) == 0  // Strings are the same up through the null terminator
memcmp(s1, s2, 8) != 0   // First 8 bytes are different
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • 1
    Thanks Adam.Your answer clarifies the use of these three functions a lot. – und3rd06012 Oct 27 '12 at 00:26
  • 1
    means memcmp is similar to strcmp, except that bytes equal to 0 are not treated as comparison terminators. So strcmp basically uses the properties of strings that terminates at null character. – Sarwan Nov 24 '14 at 12:29
  • Great answer. I just spent a couple hours trying to figure out why comparing 2 24 byte (not null terminated) strings were returning 0 about 50% of the time and returning some random value the rest of the time. memcmp was definitely what I should have been using. – mreff555 Mar 05 '20 at 14:05
10

memcmp compares a number of bytes. strcmp and the like compare strings.

You kind of cheat in your example because you know that both strings are 5 characters long (plus the null terminator). However, what if you don't know the length of the strings, which is often the case? Well, you use strcmp because it knows how to deal with strings, memcmp does not.

memcmp is all about comparing byte sequences. If you know how long each string is then yeah, you could use memcmp to compare them, but how often is that the case? Rarely. You often need string comparison functions because, well... they know what a string is and how to compare them.

As for any other issues you are experiencing it is unclear from your question and code. Rest assured though that strcmp is better equipped in the general case for string comparisons than memcmp is.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • Let me ask in a different way.What will happens if I use memcmp and I initialize word1 to "atomr" and word2 to "atoms".Will it return 0 or not? – und3rd06012 Oct 26 '12 at 23:37
  • @el10780: That depends on what length you pass to it. If you ask `memcmp` to compare 4 or fewer bytes, then it will return 0 (equal); if you ask it to compare 5 or more bytes, then it will return non-0 (unequal). – Adam Rosenfield Oct 26 '12 at 23:41
  • Forgive my ignorance,but I wasn't able to understand the difference between "atoms" and "atomr" in terms of byte sequence.They do have the same size right?But the byte sequence for "atomr" is 97,116,111,109,114 and for "atoms" is 97,116,111,109,115.So for memcmp if it checks all five characters it won't return 0.Anyway,thank you for your quick replies and help. – und3rd06012 Oct 26 '12 at 23:49
3

To summarize:

  • strncmp() and strcmp() treat a 0 byte as the end of a string, and don't compare beyond it

  • to memcmp(), a 0 byte has no special meaning

Chad
  • 1,750
  • 2
  • 16
  • 32
2

strcmp():

  • It is used to compare the two string stored in two variable, It takes some time to compare them. And so it slows down the process.

strncmp():

  • It is very much similar to the previous one, but in this one, it compares the first n number of characters alone. This also slows down the process.

memcmp():

  • This function is used compare two variables using their memory. It doesn't compare them one by one, It compares four characters at one time. If your program is too concerned about speed, I recommend using memcmp().
Community
  • 1
  • 1
Arvind kr
  • 103
  • 1
  • 3
  • 12
  • 9
    -1 because this is incorrect and makes a TON of baseless assumptions regarding the speed and implementation of those functions. (e.g. speed of strcmp and strncmp) (e.g. implementation of memcmp reading words at a time). Doesn't answer the question properly at all. – Wiz Jan 28 '15 at 23:05
  • 5
    On the contrary to Wiz argument, Arvid is the only one who explained the massive speed advantages of memcmp over strncmp. He just didn't mention alignment optimizations. memcmp in most compilers does compare words not chars. So it may overshoot the string leading to valgrind warnings. You don't really need to explain the difference of buffers over strings. – rurban Jun 21 '16 at 07:55
  • It is ridiculous to try to argue the difference is like that. The sole difference with modern libcs between memcmp and strcmp is that strcmp has to check whether it has to stop, which takes a little more time than only comparing bytes. I have personally benchmarked this and only measured a difference of ~10% in speed between memcmp and strcmp – Gabriel Ravier Jan 31 '21 at 10:07
  • @GabrielRavier if you have to make a lot of comparisons and you know the size of the strings then 10% isn't that minimal if you ask me – Tachi May 11 '22 at 16:15
  • 1
    @Tachi The problem is that the formulation of the post is extremely sloppy and gives very wrong indications about the best method to use. Your advice is valid but the answer implies that `memcmp` has some kind of massive speed bonus over `strncmp`, and 10% isn't that – Gabriel Ravier May 11 '22 at 23:02
1

strncmp and memcmp are same except the fact that former takes care of NULL terminated string.

prashant
  • 59
  • 7
1

For strcmp you'll want to be only comparing what you know are going to be strings however sometimes this is not always the case such as reading lines of binary files and there for you would want to use memcmp to compare certain lines of input that contain NUL characters but match and you may want to continue checking further lengths of input.