我正在尝试逐行读取文件,并将该行数据存储在名为“命令”的对象中(其中包含有关机器人对象可以理解哪些指令的信息)
这是读取函数(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_size
和cmd_count
因为 vector 本身通过size()
提供这些信息和capacity()
成员函数。std::ifstream
而不是FILE*
.在循环中读取输入时,您应该只使用std::string
而不是char[161]
,尽管我不确定这部分,因为我不确切知道您正试图从流中读取哪些数据。
关于c++ - 整数递增使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9881945/