【问题标题】:Unknown Runtime When Using c++11 instead if c++14使用 c++11 而不是 c++14 时的未知运行时
【发布时间】:2021-05-24 08:51:51
【问题描述】:

我在编译代码时遇到了以下错误。我试图通过我的代码查找转换错误,但我没有看到它。

编译在编译和运行时发生错误 g++ (GCC) 8.3.1 20191121(红帽 8.3.1-5)

当我在 Ubuntu 上编译时,我没有收到任何错误并且它运行。 (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0

这是错误。

/builddir/build/BUILD/gcc-8.3.1-20191121/obj-x86_64-redhat-linux/x86_64-redhat-linux/libstdc++-v3/include/bits/basic_string.h:1067: std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator[](std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference = char&; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type = long unsigned int]: Assertion '__pos <= size()' failed.
Aborted (core dumped)

main.cpp


//Here is where I can take a string and generate a pseudo-random password from it 
std::string passGen(std::string user)
{
    char passwordArray[9];
    int achar;
    srand (time(0));    
    for (int x=0; x <= 8; x++)
    {
        achar = (user[x] * (rand()%100))%26 + 97;
        passwordArray[x] = (char)achar;
    }   
    return passwordArray;
}
        
//This reads the filename that is passed in and builds the linked list of names and uses the password generator and generates passwords for each username. 
void readFile(std::string newFile){
    ifstream inFile(newFile);
    std::string firstWord;
    
    while(inFile >> firstWord)
    {
        listOfNames->InsertAtHead(firstWord, passGen(firstWord));
        inFile.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    inFile.close();
}

【问题讨论】:

  • “我所有的头文件和类文件。”——不,请将其缩减为minimal reproducible example,而不是期望陌生人会费力地读完几百行代码。请重访How to Ask
  • “未知语法”是什么意思?您似乎遇到了运行时错误。
  • 看起来std::string::operator[]的索引无效

标签: c++ string c++11 runtime-error


【解决方案1】:

我发现问题出在哪里。在这里:

{
    char passwordArray[9];
    int achar;
    srand (time(0));    
    for (int x=0; x <= 8; x++)
    {
        achar = (user[x] * (rand()%100))%26 + 97;
        passwordArray[x] = (char)achar;
    }   
    return passwordArray;
}

当我将短于 9 个字符的名称传递给此方法时发生错误。如果名称太短,则 user[x] 将无权访问。我不得不将其更改为

user[x % user.size()]

我没有意识到编译器之间存在如此大的差异。看到我的错误后,我很惊讶它在 Ubuntu 中成功运行。

【讨论】:

  • 未定义的行为就是:未定义。不仅仅是编译器之间的不同,它可以在同一个编译器上使用不同的标志,甚至使用相同的标志,但在不同的运行中不同。
猜你喜欢
  • 2015-07-09
  • 2017-06-18
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
  • 2013-11-06
  • 1970-01-01
  • 2017-03-20
相关资源
最近更新 更多