Aside from errors mentioned by others, you are supposed to compare the characters as unsigned char. This gets important once you go beyond ASCII-7, your results will be wrong if you don't.

The following is my own (tested) implementation (from my original work on PDCLib, which is CC0 licensed).

int strncmp( const char * s1, const char * s2, size_t n )
{
    while ( n && *s1 && ( *s1 == *s2 ) )
    {
        ++s1;
        ++s2;
        --n;
    }
    if ( n == 0 )
    {
        return 0;
    }
    else
    {
        return ( *(unsigned char *)s1 - *(unsigned char *)s2 );
    }
}
Answer from DevSolar on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › home › c_standard_library › c strncmp function
C strncmp Function
August 29, 2012 - The C library strncmp() function is used to compare at most a specified number of characters from two null-terminated strings. This string is also known as end of the string i.e.
🌐
Cppreference
cppreference.com › w › c › string › byte › strncmp.html
strncmp - cppreference.com
#include <stdio.h> #include <string.h> void demo(const char* lhs, const char* rhs, int sz) { const int rc = strncmp(lhs, rhs, sz); if (rc < 0) printf("First %d chars of [%s] precede [%s]\n", sz, lhs, rhs); else if (rc > 0) printf("First %d chars of [%s] follow [%s]\n", sz, lhs, rhs); else printf("First %d chars of [%s] equal [%s]\n", sz, lhs, rhs); } int main(void) { const char* string = "Hello World!"; demo(string, "Hello!", 5); demo(string, "Hello", 10); demo(string, "Hello there", 10); demo("Hello, everybody!"
🌐
BeginnersBook
beginnersbook.com › 2017 › 11 › c-strncmp-function
C strncmp() Function with example
#include <stdio.h> #include <string.h> int main () { char str1[20]; char str2[20]; int result; strcpy(str1, "hello"); strcpy(str2, "helLO WORLD"); //This will compare the first 4 characters result = strncmp(str1, str2, 4); if(result > 0) { printf("ASCII value of first unmatched character of str1 is greater than str2"); } else if(result < 0) { printf("ASCII value of first unmatched character of str1 is less than str2"); } else { printf("Both the strings str1 and str2 are equal"); } return 0; }
🌐
Wikibooks
en.wikibooks.org › wiki › C_Programming › string.h › strncmp
C Programming/string.h/strncmp - Wikibooks, open books for an open world
int strncmp (const char * const s1, const char * const s2, const size_t num) { const unsigned char * const us1 = (const unsigned char *) s1; const unsigned char * const us2 = (const unsigned char *) s2; for(size_t i = (size_t)0; i < num; ++i) { if(us1[i] < us2[i]) return -1; else if(us1[i] > us2[i]) return 1; else if(! us1[i]) /* null byte -- end of string */ return 0; } return 0; } In practice, however, real implementations are significantly optimized.
🌐
W3Schools
w3schools.com › c › ref_string_strncmp.php
C string strncmp() Function
The strncmp() function compares the first n characters of two strings and returns an integer indicating which one is greater.
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 168019-strncmp-implementation-help.html
Strncmp implementation help
In the loop in your function where do you ever test to see the characters in both string are equal, less than, or greater than each other? Jim ... #include <stdio.h> #include <string.h> #undef strncmp int strncmp(const char *s, const char *t, size_t num) { for ( ; num >0; s++, t++, num--) if (*s == 0) return 0; if (*s == *t) ++s; ++t; else if (*s != *t) return *s - *t; } int main () { char str[][5] = { "R2D2" , "C3PO" , "R2A6" }; int n; puts ("Looking for R2 astromech droids..."); for (n=0 ; n<3 ; n++) if (strncmp (str[n],"R2xx",2) == 0) { printf ("found %s\n",str[n]); } return 0; }
Find elsewhere
🌐
W3Resource
w3resource.com › c-programming › string › c-strncmp.php
C strncmp() function
It uses the print_result function to output whether the strings are identical, less than, or greater than each other based on the specified comparison length. ... #include <stdio.h> #include <string.h> #define SIZE 10 int main(void) { int result; ...
🌐
Aticleworld
aticleworld.com › home › how to use and implement own strncmp in c
How to use and Implement own strncmp in C - Aticleworld
August 23, 2020 - The strncmp function compares not more than n characters (characters that follow a null character are not compared) from the array pointed to by s1 to the array pointed to by s2. int strncmp(const char *s1, const char *s2, size_t n);
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › stdstrncmp-in-c
std::strncmp() in C++ - GeeksforGeeks
July 2, 2024 - This function is a Standard Library function that is defined in <cstring> header file in C++. int strncmp(const char *str1, const char *str2, size_t count);
Top answer
1 of 2
2

What does strncmp actually do?

strncmp compares the first two characters in the strings. (When comparing characters, it uses their values as unsigned char, even though they are passed via pointers to char.) If the characters differ or either is a null character:

  • If the character from the first string is greater than the character from the second, strncmp returns a positive value.
  • If the first is less than the second, strncmp returns a negative value.
  • Otherwise (the characters are both null characters), strncmp returns zero.

If the characters did not differ and neither was a null character, strncmp goes on to compare the following characters in the same way, until n pairs have been compared. If no difference has been found after n pairs have been compared, strncmp returns zero.

Some implementations of strncmp may return the signed difference between the two characters that differed, but this is not required by the C standard. strncmp may simply return +1 and −1 for “greater than” and “less than” or may use other positive and negative values.

2 of 2
1

strncmp(s1, s2, n) compares up to n characters from the strings pointed to by s1 and s2. It stops if it finds a difference and returns a negative value if the character from s1, converted to an unsigned char is less than the corresponding character from s2 (also converted to an unsigned char) and a positive value it is is greater. Subtracting the values of the differing characters is a handy way to compute a return value with the correct sign.

If no difference was found before the end of both strings or n characters have been processed, whichever comes first, it returns 0.

Your code has some small issues:

  • the pointer arguments should be declared with type const char * and n with type size_t.
  • similarly, i should be defined as a size_t, defining it as an int forces you to use a cast in the comparison and will cause undefined behavior for strings with an identical prefix longer than INT_MAX and a large enough n argument.
  • you should not dereference s1[i] nor s2[i] if n has reached 0, so the test on n should be performed first.
  • the difference should be computed as diff = (unsigned char)s1[i] - (unsigned char)s2[i];
  • note also that on some very exotic platforms, where sizeof(char) == sizeof(int), the subtraction cannot be used as it may wrap around and produce incorrect results.
  • it is preferable to not use names reserved for standard functions for your own versions and it may cause clashes with the compiler's intrinsics.

Here is a modified version:

#include <stdio.h>

int my_strncmp(const char *s1, const char *s2, size_t n) {
    for (size_t i = 0; i < n; i++) {
        int diff = (unsigned char)s1[i] - (unsigned char)s2[i];
        if (diff != 0 || s1[i] == '\0')
            return diff;
    }
    return 0;
}

int main() {
    char s11[] = "abcs";
    char s12[] = "zzfs";
    size_t n = 3;
    printf("   strncmp() -> %d\n", strncmp(s11, s12, n));
    printf("my_strncmp() -> %d\n", my_strncmp(s11, s12, n));
    return 0;
}

The output values may differ but should have the same sign or should both be null.

🌐
Cplusplus
cplusplus.com › reference › cstring › strncmp
strncmp - cstring
strncmp · function · <cstring> int strncmp ( const char * str1, const char * str2, size_t num ); Compare characters of two strings · Compares up to num characters of the C string str1 to those of the C string str2. This function starts comparing the first character of each string.
🌐
OpenGenus
iq.opengenus.org › strncmp-in-c
strncmp in C
November 6, 2019 - strncmp is a function in C which is used to compare two array of characters upon N indexes and return if the first array is less, equal or greater than the second array.
🌐
FreeBSD
forums.freebsd.org › development › userland programming and scripting
C - strcmp in the C standard? | The FreeBSD Forums
August 13, 2022 - FreeBSD’s libc implementation of strcmp() appears to find the first two characters that differ, and return the difference between them. Whereas valgrind’s strcmp() only returns a value from the...
🌐
O'Reilly
oreilly.com › library › view › c-in-a › 0596006977 › re225.html
strncmp - C in a Nutshell [Book]
December 16, 2005 - char *weekdays[ ] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; char date[ ] = "Thu, 10 Mar 2005 13:44:18 +0100"; int dow; for ( dow = 0; dow < 7; dow++ ) if (strncmp( date, weekdays[dow], 3 ) == 0 ) break;
Authors   Peter PrinzTony Crawford
Published   2005
Pages   618
Top answer
1 of 2
7

I think you've misinterpreted the definition of strncat, which says,

Appends the first num characters of source to destination, plus a terminating null-character. If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.

n is the maximum number of characters in source you you want to copy, and bfsize doesn't exist in the standard version of strncat.

char destination[256];
strpy(destination, "foo");
strncat(destination, "bar", 2);
// expect destination should now contain "fooba" !

It's good of you to write a custom version with an extra parameter to make it safe, but that's not what the question asked for.

See also Manual Reference Pages - Strn (3) (e.g. Strncat instead of strncat); or, the Microsoft versions of the 'safe' functions have _l as a suffix.

I'm not sure that returning null and doing no copy is the standard way to avoid buffer overflow.


In your custom_strncmp method, I'm not sure what correct behaviour should be if you call

strncmp("foo", "foo", 10);

Your function might return 0 or non-zero, or crash, depending on what's after the end of the string.

You could perhaps write it more elegantly as a for loop:

for ( ; n--; ++s, ++t) {
    if(*s != *t) {
        return *s - *t;
    }
}

In custom_strncat you don't handle the condition where n > strlen(t).


Your parameters could (should) be better named, e.g. source and destination. Parameter names are important (even more important than good names for local variables) because they may be the only documentation about how the function should be called.

2 of 2
4

Years later, but for completeness ... custom_strncpy above is not compatible with standard strncpy.

  1. It writes n+1 characters into destination (only n is correct).
  2. It reads past \0 of source string.
  3. It does not \0-pad destination string if source is smaller.
  4. it always \0 terminates. (strncpy will not in case strlen(source) >= s).
🌐
Javatpoint
javatpoint.com › strncmp-function-in-c
Strncmp() function in C - javatpoint
Strncmp() function in C with Tutorial, C language with programming examples for beginners and professionals covering concepts, c pointers, c structures, c union, c strings etc.