I developed a code for the exercise of isogram. The codes compiles perfectly with online gdb compiler but here it creates an error of segmentation fault, I don’t understand why. I am attaching my code below for reference and requesting for some support here.
#include "isogram.h"
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool is_isogram(char phrase[])
{
int is_char_uniq=0;
int len_of_strin = strlen (phrase);
for (int i=0; i< len_of_strin; i++)
{
for (int j=i; j<len_of_strin; j++)
{
if (j!=i)
{
if (phrase[i] != phrase[j])
{
is_char_uniq =1;
}
else
{
is_char_uniq =0;
return false;
}
}
}
}
if (is_char_uniq == 1)
{
return true;
}
return false;
}
If you show me the code and the error message I will try my best to help you.
Edit:
I just took the code that you posted above and inserted my two lines at the beginning of the function. The segmentation fault disappeared, there are now more “normal” test failures.
In case you replaced the contents of the previous expression, i.e.
if (strlen (phrase)<=0)
return false;
with this:
if (phrase == NULL)
return false;
then try adding the second snippet above the first. You need both
The second one is necessary because in C, arrays are referenced by pointer (i.e. memory address), and dereferencing a pointer of address 0x0 (NULL) (which happens in strlen) causes the processor to “panic”, and run a special procedure of the operating system that closes down the program. So while the NULL-pointer is a legal type of argument, it is not a valid address, so the program crashes on runtime. In C we use NULL for something uninitialized and/or error control flow. I hope that makes sense
Edit: You can combine them though, such as:
if (!phrase || strlen(phrase) == 0)
return false;
In the above if-statement, the first part of the expression is evaluated first, and the second is only evaluated if the first one is false - so it should be safe. phrase is casted to true if it is non-NULL, so we just negate the result with !. Also, no need to check if the string length is less than zero.