如何修复严重的段故障

时间:2019-05-22 07:51:26

标签: c++ segmentation-fault strlen

我正在尝试获取哈希函数的键的字符串长度,并且在我尝试使用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>

这是我在读取char键的地方:

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');

1 个答案:

答案 0 :(得分:2)

strlen documentation这样说:

  

返回给定字节字符串的长度,即   字符数组中第一个元素由指向的字符   延伸到且不包括第一个空字符。该行为是   如果指向的字符数组中没有空字符,则未定义   到str。

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