简体   繁体   English

strchr导致C中的分段错误

[英]strchr causing segmentation fault in C

I am having problem with a C program. 我在使用C程序时遇到问题。 I know that strchr() is causing the problem, and it is returning 我知道strchr()引起了问题,并且正在返回

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. strchr函数在字符串中搜索c的首次出现。 The null character terminating string is included in the search. 搜索中包括空字符终止字符串。

Are you sure that your string is legal? 您确定您的字符串合法吗? (meaning ending with null) (表示以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. strchr(char * string,int c)函数返回一个指针,该指针指向字符串中字符c的第一个匹配项;如果找不到匹配的字符,则返回NULL指针。

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): 两种方法之一(如果不应传入NULL ):

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 "" ): 或平滑的方式(将NULL""静默地对待):

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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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