【问题标题】:c++ program crash when using regex使用正则表达式时c ++程序崩溃
【发布时间】:2014-11-28 18:27:48
【问题描述】:

我的代码在到达正则表达式部分时编译崩溃:

我想检查接收到的字符串中是否存在任何数字。

#include <iostream>
#include <regex>
using namespace std;

int main()
{
    int in, count, rate;
    char *w;
    cin >> count;

    for(in = 1; in < 5; in++) {
        rate = 0;
        cin >> w;
        cout << "Case #";
        cout << in;
        cout << ":";

        if (regex_match (std::string(w), regex("([0-9])")))
            ++rate;
        cout << rate;
        cout << endl;
    }
    return 0;
}

【问题讨论】:

  • 那么你在哪里为char * 变量分配内存?弄清楚之后,别忘了也释放它......

标签: c++ regex gcc g++ mingw32


【解决方案1】:

您正在使用没有分配内存的指针。这将使您的程序崩溃。只需将其声明为字符串,并尽量避免裸指针:

std::string w;

【讨论】:

  • 现在正则表达式中的 [0-9] 崩溃。当我改变它时,程序工作正常
【解决方案2】:

为避免功能出现此类错误,请开启警告,即-Wall:

main.cpp:6:18: warning: 'w' is used uninitialized in this function [-Wuninitialized]
     cin >> w;

在使用w之前,需要为其分配内存。通常在 C 风格的代码中,您可以使用具有自动存储功能的数组:

char w[80]; // some arbitrary number guaranteed to be large enough to hold
            // user input

或动态内存:

char* w = new char[80];
// ...
delete[] w;

正如另一个答案中所述,在 C++ 中使用 std::string 更为惯用,因为它会为您处理内存。这也避免了您稍后在代码中创建所有那些不必要的临时对象:

if (regex_match (std::string(w), regex("([0-9])")))
// ~~~~~~~~~~~~~~^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    相关资源
    最近更新 更多