Search code examples
carraysstringpointersstrcmp

String Comparison Discrepancy (Works for some cases and sometimes doesn't)


I used the following code to test some text detection from an email file that I received.

#include <stdio.h>

int main()
{
  int max_size = 100;
  char email[100] ="aheanstring4strinstringzil.comg";
  int pointer = 0;
  int i = 1;
  int j = 0;
  int len = 0;
  int chk = 0;
  char found1[7] = "string1";
  char found2[7] = "string2";
  char found3[7] = "string3";
  char found4[7] = "string4";
  char found5[7] = "string5";

  char user1[7] = "string1"; // 23        
  char user2[7] = "string2";// 19        
  char user3[7] = "string3"; // 14        
  char user4[7] = "string4"; // 16      
  char user5[7] = "string5";; // 15

  while (pointer != max_size && chk != 1)
  {

    for (j = 0;j<7; j++)
    {
      found1[j] = *(email+pointer+j);
    }

    if (strcmp(found1, user1) == 0){
      printf("Authorized User Found\n");
      chk = 1;
      continue;
    }

    for (j = 0;j<7; j++)
    {
      found2[j] = *(email+pointer+j);
    }

    if (strcmp(found2, user2) == 0){
      printf("Authorized User Found\n");
      chk = 1;
      continue;
    }

    for (j = 0;j<7; j++)
    {
      found3[j] = *(email+pointer+j);
    }

    if (strcmp(found3, user3) == 0){
      printf("Authorized User Found\n");
      chk = 1;
      continue;
    }

    for (j = 0;j<7; j++)
    {
      found4[j] = *(email+pointer+j);
    }

    if (strcmp(found4, user4) == 0){
      printf("Authorized User Found\n");
      chk = 1;
      continue;
    }


    for (j = 0;j<7; j++)
    {
      found5[j] = *(email+pointer+j);
    }

    if (strcmp(found5, user5) == 0){
      printf("Authorized User Found\n");
      chk = 1;
      continue;
    }

    pointer++;

  }
  printf("Check is %d, Pointer is %d\n",chk, pointer);
  return 0;
}

I use the above code to look for certain users in an email body. If a user is found, the while loop breaks. When I tried running it, I included the different strings in the above variable (email)

I tried running it first on different online C-compilers. All of them had strings 1,3, and 5 working fine. (being detected)

Some of them had string 2 working fine (being detected).

However, ALL of them shared the fact that string2 is never detected. I don't know why. I tried thinking of a reason but couldn't figure out why.

I would really appreciate some help.


Solution

  • char found1[7] = "string1";
    

    Here found1 is not a valid string in C since there is no nul termination. You need to have

    char found1[8] = "string1";
    

    You pass found1 to strcmp() which will lead to undefined behavior since strcmp() expects a null terminated string.

    or as @Barak Manos suggested you can go for

    char found1[] = "string1";