c++ - 整数递增使应用程序崩溃

标签 c++

我正在尝试逐行读取文件,并将该行数据存储在名为“命令”的对象中(其中包含有关机器人对象可以理解哪些指令的信息)

这是读取函数(C++):

int robot::readfile(const char fname[]) {
    FILE *rf;
    rf = fopen(fname, "r");

    if (rf != NULL) {
        int idx = 0;
        char record[161];

        while ((this->cmd_count < this->cmd_size)
               && (fgets(record, 160, rf) != NULL)) {
            command tmp_cmd(record);
            this->cmds[idx++] = tmp_cmd;
        }
    } else {
        perror(fname);
    }

    fclose(rf);
    return 1;
}

基本上,在上面的代码中,当我尝试将变量“idx”递增 1(使用语法:idx++)时,它基本上只会让应用程序崩溃。

有什么想法吗?

编辑: 根据评论者的要求:

void robot::cmd_malloc(int size) {
    // most likely will cause problems if size is below 1.
    if (size < 1) {
        return;
    }

    try {
        this->cmds = new command[size];
        this->cmd_size = size;
        this->cmd_count = 0;
    } catch (std::bad_alloc) {
        // bad allocation exception.
        this->cmds = NULL;
        cout << "bad_alloc:" << (sizeof(command) * size) << " in 'robot::cmd_malloc'." << endl;
    }

}

最佳答案

您没有递增 cmd_count在循环中,这意味着在某个时刻 idx变得大于 cmd_size这会导致程序崩溃。

编写代码的 C++ 风格是使用:

  • std::vector<command>而不是 new command[size] .如果你使用 std::vector ,那么你就不必自己进行内存管理,而且你不必维护另外两个变量 cmd_sizecmd_count因为 vector 本身通过 size() 提供这些信息和 capacity()成员函数。

  • std::ifstream而不是 FILE* .在循环中读取输入时,您应该只使用 std::string而不是 char[161] ,尽管我不确定这部分,因为我不确切知道您正试图从流中读取哪些数据。

关于c++ - 整数递增使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9881945/

相关文章:

c++ - fatal error : libavfilter/avfiltergraph. h:没有这样的文件或目录

c++ - 提取单个像素数据的最快方法?

c++ - WS_EX_LAYERED 窗口不接收鼠标事件

c++ - 使用 CMake 生成 32 位/64 位 Eclipse CDT 项目

C++11 统一初始化 : Field initializer is not constant

c++ - C/C++ 程序在冒泡排序时崩溃

c++ - 解释这些分组函数的时间复杂度

c++ - 将 Qt 添加到现有的 Visual Studio c++ 项目

c++ - 在 C++ 中循环两个 vector

c++ - Qt Widgets 和派生类