c++ - 如何修复双重释放或损坏错误

标签 c++

我在打开不存在的打印机时遇到错误。找到打印机后,我的应用程序工作正常。但是当没有找到打印机时,我遇到了 double free or corruption 错误。 下面是我的代码:

#define BUFSIZE 200

FILE *pPortFile = NULL;

void Printer::closePrinter()
{
    if (pPortFile != NULL)
    {
        fclose(pPortFile);
        pPortFile = NULL;
    }
}

void Printer::openPrinter(string sPortName)
{
    struct stat tFilest;
    int iFileDescriptor = 0, i = 0;
    char aResponse[BUFSIZE] = {0}, aFName[BUFSIZE];

    ePrinterType_ = UNKNOWN;

    closePrinter();

    pPortFile = popen("find /sys/devices/platform -name lp0 -print", "r");

    if (pPortFile != NULL)
    {
        i = fread(aResponse, sizeof(char), BUFSIZE - 1, pPortFile);

        aResponse[i] = '\0';

        if(i != 0)
        {
            pclose(pPortFile);
            strcpy(aFName, dirname(aResponse));
            strcat(aFName, "/../../idProduct");
            pPortFile = fopen(aFName, "r");            

            if (i != 0 && pPortFile != NULL)
            {
                i = fread(aResponse, sizeof(char), BUFSIZE - 1, pPortFile);
                aResponse[i] = '\0';

                if (strstr(aResponse,"3538"))
                    ePrinterType_ = PRINTER_1;
                else if (strstr(aResponse,"2305"))
                    ePrinterType_ = PRINTER_2;
            }

            fclose(pPortFile);
        }

        pclose(pPortFile);

    }

    if(ePrinterType_ == UNKNOWN)
    {
        cout << "printer not found" << endl;
        throw Exception("Printer not found");
    }
    else
    {
        pPortFile = fopen(sPortName.c_str(), "r+");
        iFileDescriptor = fileno(pPortFile);
    }
}

我在这一行之后遇到双重释放或损坏 (!prev) 错误:

if(ePrinterType == UNKNOWN)
{
    cout << "printer not found" << endl;
    throw Exception("Printer not found");
}

我找不到实际发生错误的地方。请帮忙

最佳答案

看看这些行——你真的想全部都做吗——解释你为什么要这样做……

        pclose(pPortFile);
        ...
        fclose(pPortFile);
    ...
    pclose(pPortFile);

关于c++ - 如何修复双重释放或损坏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59299202/

相关文章:

使用自定义类类型作为键的 C++ unordered_map

c++ - 分离到.h/.cpp后重定义Class

c++ - 委托(delegate)对象销毁

c++ - FMOD 3D 声音监听器中“使用了无效的对象句柄”

c++ - 配置 : error: no boost. 找到文件系统库

c++ - Building Boost - 找不到 windows.h

c++ - GDB:我们如何从 std::tuple 中提取值

c++ - Armadillo :从稀疏矩阵中获取稀疏行 vector 的非零位置

c++ - NS3 添加新模块 - gcc 未找到包含的 header

c# - 托管 C dll 调用 C# dll,FileNotFoundException