0

I have simple string comparison routine. Recently added string keyboard input, but something is wrong. Function "cmp("ala", dict);" works just fine. I suspect zero-termination issue related to strings in general, or some buffer length incompatibility.

Search input "ala" returns no hit. But (after commenting unnecessary code) this is ok "cmp("ala", dict);"

This is the code.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *MyText[256];
char **dictionary()
{
    char **dict = (char**)malloc(sizeof(char*) * 5);
    int i = 0;
    for(i = 0; i < 5; i++)
        dict[i] = (char*)malloc(sizeof(char) * 7);
    strcpy(dict[0], "mark");
    strcpy(dict[1], "ala");
    strcpy(dict[2], "wojtek");
    strcpy(dict[3], "tom");
    strcpy(dict[4], "john");
    
    return (dict);
}
void free_dictionary(char **dict)
{
    for (int i = 0; i < 5; i++)
        free(dict[i]);
    free(dict);
}

int cmp(char *s1, char *s2[5])
{
    int i = 0;
    int n = 0;
  
    for (i = 0; i < 5; i++)
        if (strcmp(s1, s2[i]) == 0) {
            
            n++;
            
        }
    if (n > 0)
        printf("Found %d", n);
    else
        printf("Nothing found");
}

int main(int argc, char *argv[])
{

    char BufText[255];
    int n=0;
    char sign;
    fflush(stdin);
    printf("Give me names: \n");
    n = 0;
    do {
        sign = getchar();
        BufText[n ++] = sign;
        if(n >= 253) break;
    } while (sign !='\n');
    BufText [n] = 0;
    char **dict = dictionary();
    cmp(BufText, dict);
    free_dictionary(dict);
    return 0;
}
kaylum
  • 13,833
  • 2
  • 22
  • 31
  • 1
    "something is wrong". Don't make us guess. Please tell us exactly what problems you are having. That is, give the input, expected result and actual result. – kaylum Aug 07 '20 at 06:13
  • [`fflush(stdin);` is undefined behaviour, don't do it.](https://stackoverflow.com/a/38325926/2173917)"} – Sourav Ghosh Aug 07 '20 at 06:13
  • sorry for that, the search input "ala" returns no hit. But (after commenting unnecessary code) this is ok "cmp("ala", dict);" – Wojciech Mierzejewski Aug 07 '20 at 06:24
  • Looks like you are storing `\n` into the `BufText`. Suggest doing basic debugging such as running in a debugger and/or adding debug print statement. – kaylum Aug 07 '20 at 06:41

1 Answers1

0

The user input is saved with the ' \n' character. Consequently, your string compare will not match, i.e "ala" does not match "ala\n".

Check for '\n' before adding to the buffer to avoid saving the newline character.

For instance:

n = 0;
do {
    sign = getchar();
    if (n >= 253) break;
    if (sign =='\n') break;
    BufText[n ++] = sign;
} while (1);
BufText [n] = 0;

or in a more compact form:

n = 0;
while (n < 253 && (sign = getchar()) != '\n') BufText[n ++] = sign;
BufText [n] = 0;
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63