Search code examples
cpointersdereference

Segmentation fault in C when trying to reference first element in char *


I have written a C function which the goal in mind to see if the chars 'b' is in the char array 'a'. I am new to pointers and learning.

void contains (char const *a, char const *b)
{

}

and am calling it as:
contains("abc", "b");

From my understanding (what I've read so far), the first element of the char[] of 'abc' should be 'a'.

So if I reference: 
*a, it should equal 'a'. Which I tested with:
printf("%s", (*a == 'a')? "true\n" : "false\n");

And it printed true, which is cool. 

The issue is if I try:

printf(*a);
I get: Run Command: line 1:  8769 Segmentation fault: 11  ./"$2" "${@:3}"

What am I doing wrong here? The goal is to get the reference to 'a' in 'abc', and check its equality to 'b'. If its not, then I want to increment via a counter to the next char in 'a' and so on.


Solution

  • printf takes a pointer as it's first argument, and you are passing a char, which is being interpreted as an address at which there is expected to be a null-terminated array of chars. The memory located at the address 'a' (i.e. hex 61) is probably not owned by your process, hence the seg fault.

    As an expansion to this answer, here is a printf call that should get you your desired inspection:

    printf("%c", *a); // to print the first char of the string at a
    printf("%s", a); // to print the full string at a