简体   繁体   中英

Segmentation fault in char array

I am trying to solve anagram problem from https://practice.geeksforgeeks.org/problems/anagram/0 . When I try in my computer with custom inputs, it works fine. But when I try it in the above link, it throws segmentation fault. What am I doing here wrong? Thanks in advance.

My code

#include <bits/stdc++.h>
int checkAnagram(char a[],char b[])
{
  int i,x=0;
  int n = strlen(a);
  int m = strlen(b);

  if(n != m)
    return -1;

  for (i = 0; i < n; i++) {
    x^=a[i];
  }
  for (i = 0; i < n; i++) {
    x^=b[i];
  }

  return x;
}
int main(int argc, char const *argv[]) {
  int t;    //No of testcases
  char a[100],b[100];
  scanf("%d", &t);
  while(t--)
  {
    scanf("%s", a);
    scanf("%s", b);
    checkAnagram(a,b) == 0?printf("YES\n"):printf("NO\n");
  }

  return 0;
}

PS - Please try it in the above link. I cant possibly know all the testcases they pass including the hidden ones.

Try this:

void checkAnagram(char a[],char b[])
{
  int n1 = strlen(a);
  int n2 = strlen(b);
  if (n1 != n2) {
    printf("NO\n");
    return;
  }
  int x=0;
  for (int i = 0; i < n1; i++) {
    x^=a[i];
    x^=b[i];
  }
  x == 0?printf("YES\n"):printf("NO\n");
}

EDIT (explanation): your arrays might differ in size. Since two different sized arrays can't be anagrams of each other, we first check for it and bail out, if size differs.

Note, that even without this logical requirement you still need to check for arrays size. You access both arrays at index i , so you need to make sure both arrays are at least that size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM