简体   繁体   中英

strchr causing segmentation fault in C

I am having problem with a C program. I know that strchr() is causing the problem, and it is returning

Segmentation Fault

My code is as follows:

char *pointer;
pointer = strchr(string, character);

I don't know why I'm getting the error message. One thing I can guess is that my 'string' sometimes doesn't contain the character. Could that be the reason why?

How can I stop it, as I don't have control over the input string?

Full code

int index(const char *string, char character)
{
    const char *pointer;
    pointer = strchr(string, character);

    if(pointer)
        return (pointer - string);
    else
        return -1;
}

First , try to print the input for your method.

From here

The strchr function searches string for the first occurrence of c. The null character terminating string is included in the search.

Are you sure that your string is legal? (meaning ending with null)

I think this what may cause your problem

The strchr(char *string, int c) function returns a pointer to the first occurrence of character c in string or a NULL pointer if no matching character is found.

Since the null character terminating string is included in the search, you have to be sure that your string is null-terminated, otherwise the search goes out of bounds.

If you'd like to print the string or performing other operations with the result, check first the pointer; in your specific case:

if(pointer != NULL)
   printf(...);
   [...]

To write save code always perform input validation:

Either the hard way (if NULL is not supposed to be passed in):

ssize_t index(const char * string, const char character)
{
  assert(NULL != string);

  const char * pointer = strchr(string, character);

  if (pointer)
  {
    return (pointer - string);
  }
  else
  {
    return -1;
  }
} 

Or the smooth way (silently treat NULL the same way as "" ):

ssize_t index(const char * string, const char character)
{
  const char * pointer = NULL;

  if (string)
  {
    pointer = strchr(string, character);
  }

  if (pointer)
  {
    return (pointer - string);
  }
  else
  {
    return -1;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM