Question: I have the following function, and I want to test if the two strings are anagrams. One way I thought about doing it would be to sum the values of each of the characters in the strings and then compare their values.

However, I am getting a segmentation fault in both the for loops when I try to run my program. I am not understanding this correctly, is there anything I am doing incorrectly in my code?

```
int anagram(char *a, char *b)
{
    int sum1 = 0;
    int sum2 = 0;
    char *p, *q;

    for (p=a; p != '\0'; p++) {
        sum1 += *p - 'a';
    }

    for (q=b; q != '\0'; q++) {
        sum2 += *q - 'a';
    }

    if ( sum1 == sum2 )
        return 1;
    else 
        return 0;
}

```

Answer: 
In your `for` loops you must check

`*p != '\0'`

`*q != '\0'`

This is the cause of the seg-fault.

---

Furthermore, even fixed, that code will give you false positives:

"bc" anagram of "ad"

I suggest you a different approach:

make two arrays of `int`s sized 256, zero initialized.

Let every item of each array keep the count of every letter (char) of each string.

Finally compare if the two arrays are the same.

I leave the task of writig the code to you.
Since we're already giving answers about better approaches, here's mine:

Get a list of (preferably small) prime numbers. You need one for every possible character of your input strings, thus when you want to check strings containing only digits 0 to 9 you need 10 prime numbers. Let's take these:

```
static unsigned const primes[10] = {
  2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

```

Now, since each number has exactly one prime factorisation, and because of multiplication being commutative, you can just build the product of the prime numbers for each character of your string. If they're identical, then for each character holds that it has been the same number of times in both strings. Thus, both strings are anagrams of each other.

```
unsigned long prime_product(char const * str) {
  assert(str != NULL);
  unsigned long product = 1;
  for (; *str != '\0'; ++str) {
    assert(*str >= '0');
    assert(*str <= '9');
    product *= primes[*str - '0'];
  }
  return product;
}

char is_anagram(char const * one, char const * two) {
  return prime_product(one) == prime_product(two);
}

```

This should even work to some extend when the product overflows, though then false positives are possible (though their likelihood can be greatly reduced when also comparing the length of the two strings).

As can be seen this version has `O(n)` time and constant space complexity.