c++ - 如何修复 strlen 段错误

标签 c++ segmentation-fault strlen

我正在尝试为我的散列函数获取我的 key 的字符串长度,并且在我尝试使用 strlen 的地方,我一直在 GDB 中收到此错误:

"_strlen_sse2 () at ../sysdeps/x86_64/multiarch/../strlen.S:79
79  ../sysdeps/x86_64/multiarch/../strlen.S: No such file or directory."

我试过运行 gdb,但不允许我使用字符串类,我知道我的程序无法通过这行代码。

int table::hashfunc(char key[])
{       
     int hash = 0;
      int k = 1;      
     int key_size = strlen(key); //PROGRAM DOESN'T RUN PAST HERE

      for(int i = 0; i < key_size; ++i)
      {       
              hash = hash + (int)key[i];
              hash = pow(hash, k);
      }
      int index = hash % SIZE;
      return index;


 }

 //This is where I call the hash function from.

int table::add_name(char character[], char movie[], char choice)
{ 
    int index = hashfunc(character);

我希望将 key_size 设置为键中的字符数,但是当我检查 gdb 中的 strlen(key) 时,我得到了这个:

 (gdb) print strlen(key)
 $1 = (size_t (*)(const char *)) 0x7ffff7156620 <__strlen_sse2>

这是我在字符键中读取的位置:

do  
     {
    cout << "Please enter the name of the film you 
would like to add to: " <<endl;
                            cin.get(temp_movie, temp_size);
                            cin.ignore(100, '\n');

                            cout << "Enter 'C' to add a character, 
enter 'A' to add an actor: " <<endl;
                            cin >> choice;
                            cin.ignore(100, '\n');
                            choice = toupper(choice);

                            cout << "Enter the name of the character or 
 actor you would like to add: " <<endl;
                            cin.get(temp_name, temp_size);
                            cin.ignore(100, '\n');

                            if(choice == 'C')    
                                    character_table.add_name(temp_name, 
 temp_movie, choice);
                            else if(choice == 'A')
                                    actor_table.add_name(temp_name, 
  temp_movie, choice);
                            else
                                    cout << "That is an invalid choice. 
 please try again." <<endl;


                    }while(choice != 'A' && choice != 'C');

最佳答案

strlen documentation是这样说的:

Returns the length of the given byte string, that is, the number of characters in a character array whose first element is pointed to by str up to and not including the first null character. The behavior is undefined if there is no null character in the character array pointed to by str.

可能您的 char key[] 缺少结尾的空字符 \0

关于c++ - 如何修复 strlen 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56251838/

相关文章:

c - gcc -O 段错误

c++ - 覆盖 vector C++

C 字符指针长度

c - strlen() 输出不正确

c - 如何为没有空字符的字符串计算 strlen?

c# - 以编程方式更改屏幕色彩平衡

c++ - Xcode 中控制台应用程序没有输出

c++ - 解决第三方构建系统的段错误

c++ - 非数字输入检查

C++ 禁止从 const char* 设置 char* 和 char[]