Andy Res Andy Res - 4 months ago 8
C Question

Counting number of times a char is in a string results in a segmentation fault (core dumped)

This is an example from a book that counts the number of times a character is in a string:

int count_x(char* p, char x){
int count=0;
while(p){
if(*p==x){
++count;
}
p++;
}
return count;
}


I call it like this:

int n = count_x("hello", 'l');


But I end up with:


Segmentation fault (core dumped)


From what I read, this might be thrown when the program is trying to access a memory area that it is not supposed to do (correct me if I am wrong).

I stepped with the debugger, and it goes something like this:

p = "hello" // And for every cycle it decreases,
p = "ello"
p = "llo"
p = "lo"
p = "o"
p = ""


and to my surprise it does not stop there, but it continues to cycle, which I suppose might be the cause of segmentation fault?

The book says that a test like
while(p)
is equivalent with
while(p!=nullptr)
, and as I understand this should be sufficient for the loop to stop when the string is consumed. Again, please correct me if I am wrong, and what can I do to fix it?

Answer
while(p)

should be

while(*p)

because p is a pointer and it will be holding address and you need to check for the \0 character which is got by dereferencing the pointer *p