I am trying to write my version of the function strncmp that already exists in the C language. Below is the solution I have found; I have tested it with a handful of cases and compared the results with the original strncmp C function and I have got same results. Please let me know if there are any flaws in my solution, any errors, etc:
/*
* IT IS ENOUGH TO CHECK IF WE REACHED THE LENGTH OF ONE
* OF THE STRINGS! :)
*/
int my_strncmp(char *s1, char *s2, unsigned int n)
{
unsigned int i;
i = 0;
while ((s1[i] == s2[i]) && (s1[i] != 0) && (i < n))
i++;
return (s1[i] - s2[i]);
}
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str1 = "Hello";
char *barrier = "XXXXXX";
char *str2 = "Hellz";
int n = -1;
int max_len = 0;
int res;
max_len = strlen(str1);
if (strlen(str1) < strlen(str2))
max_len = strlen(str2);
// making sure that n is tested way beyond the strlen of strings
max_len += 2;
while (n < max_len)
{
res = strncmp(str1, str2, n);
printf(" strncmp(\"%s\",\"%s\", %d) = %d\n", \
str1, str2, n, res);
res = my_strncmp(str1, str2, n);
printf("my_strncmp(\"%s\",\"%s\", %d) = %d\n\n", \
str1, str2, n, res);
n++;
}
return (0);
}
The type of the parameter
nand of the counterishould besize_t, notunsigned int.The type of the first two parameters should be
const char *.Although the strings are passed as pointers to
char(withconst), the characters should be interpreted as if they had the typeunsigned char, per C 2018 7.24.1 3.s1ands2should never be accessed beyondncharacters, but the code testsi < nlast, after usings1[i]ands2[i], instead of before using them.The code also accesses
s1[i]ands2[i]in thereturnstatement even if the loop terminated becauseireachedn. Besides causing the routine to access the arrays out of bounds, this also means the return value is very likely to be wrong, as it should be zero but instead will be based on evaluations of the incorrectly accesseds1[i]ands2[i].More theoretically:
charandunsigned charare the same width asintand therefores1[i] - s2[i]can overflow or wrap. Instead, the values should be compared and used to select a positive, zero, or negative return value.