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.
Here is a complete solution for your problem:

```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int cmp(const void *str1, const void *str2) {
    return (*((char*)str1) - *((char*)str2));    
}

bool areAnagram(char *str1, char *str2) {
    int n1 = strlen(str1);
    int n2 = strlen(str2);

    if (n1 != n2)
      return false;

    qsort(str1, n1, 1, &cmp);
    qsort(str2, n2, 1, &cmp);

    for (int i = 0; i < n1;  i++)
       if (str1[i] != str2[i])
         return false;

    return true;
}

int main()
{
    char str1[] = "test";
    char str2[] = "tset";
    if (areAnagram(str1, str2))
      printf("The two strings are anagram of each other");
    else
      printf("The two strings are not anagram of each other");

    return 0;
}

```