How to use and Implement own memcmp in C

implement memcmp in C

The memcmp function compares the first n characters of the object pointed to by s1 to the first n characters of the object pointed to by s2. If the n characters of s1 and s2 are the same then it returns 0, otherwise, it returns a non-zero value.

Syntax of memcmp in C:

int memcmp(const void *s1, const void *s2, size_t n);

Parameters:

s1 − This is the pointer to a block of memory.

s2 − This is the pointer to a block of memory.

n − This is the number of bytes to be compared.

Return:

The memcmp function returns an integer greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2.

Return value Explanation
  <0 (Less than Zero)   If the first byte does not match in both memory blocks has a lower value in S1 than in S2 (if evaluated as unsigned char values)
   0 (Zero)   If the contents of both memory blocks are equal. (S1 == S2)
  >0 (Greater than Zero)   If the first byte does not match in both memory blocks has a greater value in S1 than in S2 (if evaluated as unsigned char values)

 

Let’s see an example code to understand the functionality of the memcmp in C. In this C code, we will compare two character arrays.

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

#define SIZE 15

int main ()
{
    int ret = 0;
    char s1[SIZE] = "Hello";
    char s2[SIZE] = "Aticleworld";

    ret = memcmp(s1, s2, 5);
    if(ret > 0)
    {
        printf("s2 is less than s1");
    }
    else if(ret < 0)
    {
        printf("s1 is less than s2");
    }
    else
    {
        printf("s1 is equal to s2");
    }

    return 0;
}

Output:

s2 is less than s1

Explanation: “Hello” is greater than “Aticleworld” because the first non-matching character in both words is ‘H’ and ‘A’ respectively, and ‘H’ (72) evaluates as greater than ‘A’ (65).

 

Some important points related to memcmp in C:

 

1.) We must include string.h header file before using the memcmp function in C.

2.) memcmp() compares the two memory block characters by character starting from the first to n character.

3.) If the first character in both memory blocks is equal, then this function will check the second character, if this is also equal then it will check the third and so on.

4.) If both memory block is identical till n characters, then memcmp return 0. Let’s see an example  C code where I am comparing arr1[0],arr1[1] with second integer array element arr2[0], arr2[1].

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

int main ()
{
    int ret = 0;
    int arr1[] = {1,2,3,4};
    int arr2[] = {1,2,3,4};

    ret = memcmp(arr1, arr2, sizeof(int)*2);
    if(ret > 0)
    {
        printf("arr2 is less than arr1");
    }
    else if(ret < 0)
    {
        printf("arr1 is less than arr2");
    }
    else
    {
        printf("arr1 is equal to arr2");
    }

    return 0;
}

Output:

arr1 is equal to arr2

 

5.) When the first non-matching character of buffer1 is greater than the corresponding character of buffer2, then it returns a value greater than zero. Let’s see an example  C code where I am comparing arr1[0],arr1[1] with second integer array element arr2[0], arr2[1].

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

int main ()
{
    int ret = 0;
    int arr1[] = {2,2,3,4};
    int arr2[] = {1,2,3,4};

    ret = memcmp(arr1, arr2, sizeof(int)*2);
    if(ret > 0)
    {
        printf("arr1 is greater than arr2");
    }
    else if(ret < 0)
    {
        printf("arr1 is less than arr2");
    }
    else
    {
        printf("arr1 is equal to arr2");
    }

    return 0;
}

Output:

arr1 is greater than arr2

 

6.) When the first non-matching character of buffer1 is lesser than the corresponding character of buffer2, then it returns a value less than zero. Let’s see an example  C code where I am comparing arr1[0],arr1[1] with second integer array element arr2[0], arr2[1].

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

int main ()
{
    int ret = 0;
    int arr1[] = {1,2,3,4};
    int arr2[] = {2,2,3,4};

    ret = memcmp(arr1, arr2, sizeof(int)*2);
    if(ret > 0)
    {
        printf("arr1 is greater than arr2");
    }
    else if(ret < 0)
    {
        printf("arr1 is less than arr2");
    }
    else
    {
        printf("arr1 is equal to arr2");
    }

    return 0;
}

Output:

arr1 is less than arr2

 

7.) It is the programmer’s responsibility to pass the valid memory for the comparison in the memcmp() function.

8.) The size of buffer1 and buffer2 must be greater than the number of bytes (n) you want to compare.

 

Note: In the case of structure you should avoid the use of memcmp because comparing structures with memcmp is sometimes unsafe due to the possibility of a garbage value in adding padding bytes.

 

How to write your own memcmp() function?

Your compiler/standard library will likely have a very efficient and tailored implementation of the memcmp() function. So if not require avoid to create own version of the memcmp function.

Note: Below function only to understand the working of memcmp. There is a lot of scenarios that are not handled in this function. You can handle the scenario as your requirement and if possible then use the standard memcmp function (library function).

int my_memcmp(const void *s1, const void *s2, int len)
{
    unsigned char *p = s1;
    unsigned char *q = s2;
    int charCompareStatus = 0;

    //If both pointer pointing same memory block
    if (s1 == s2)
    {
        return charCompareStatus;
    }

    while (len > 0)
    {
        if (*p != *q)
        {  //compare the mismatching character
            charCompareStatus = (*p >*q)?1:-1;
            break;
        }
        len--;
        p++;
        q++;
    }
    return charCompareStatus;
}

 

How it works:

The my_memcmp() function takes three arguments two void pointers (void *) for pointing to memory blocks and an integer to receive the value of n (Number of characters to compare).

In this function, we are using the if condition to handle the scenario when both pointers point to the same memory block.

//If both pointer pointing same memory block
if (s1 == s2)
{
    return charCompareStatus;
}

 

Now in the while loop, we are iterating each character of both buffers till n. If the characters are mismatched for any buffers, we compare the mismatched character and terminating the while loop.

while (len > 0)
{
    if (*p != *q)
    {  //compare the mismatching character
        charCompareStatus = (*p >*q)?1:-1;
        break;
    }
    len--;
    p++;
    q++;
}

 

Let’s write a small application to test our own created memcmp function,

#include <stdio.h>


int my_memcmp(const void *s1, const void *s2, int len)
{
    unsigned char *p = s1;
    unsigned char *q = s2;
    int charCompareStatus = 0;

    //If both pointer pointing same memory block
    if (s1 == s2)
    {
        return charCompareStatus;
    }

    while (len > 0)
    {
        if (*p != *q)
        {
            //compare the mismatching character
            charCompareStatus = (*p >*q)?1:-1;
            break;
        }
        len--;
        p++;
        q++;
    }
    return charCompareStatus;
}


int main()
{
    int ret = 0;
    //If s1 and s2 equal
    ret = my_memcmp("abc","abc",2);
    printf("ret = %d\n",ret);

    //if first char of s1 is large to s2
    ret = my_memcmp("bca","abc",2);
    printf("ret = %d\n",ret);

    //if first char of s1 is small to s2
    ret = my_memcmp("abc","bca",2);
    printf("ret = %d\n",ret);

    return 0;
}

Output:

ret = 0.
ret = 1.
ret = -1.

 

Recommended Articles for you:

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *