【问题标题】:Heap corruption while reading a file读取文件时堆损坏
【发布时间】:2016-01-31 13:38:23
【问题描述】:

Visual Studio 在调试我的程序的最开始时报告可能的堆损坏。这篇文章所做的是读取一个 .txt 文件以提供可供选择的字符串列表。

for循环顺利进行,直到程序终止并抛出错误结束。

我还将提供所有调用的函数(如果需要)。

int main() {
title_board(NULL,NULL,NULL, NULL);

// settings file
open_file(DEFAULT_SETTING);
bool generate_mistake_log=read_bool(16);
bool show_instructions=read_bool(10);
int pass_threshold=read_int(13);
t_direction trans_dir=read_t_dir(7);

int sett_lines=lines_count(DEFAULT_SETTING);
int library_verse=sett_lines-LIB_START_VERSE;
string *file_library=new string[library_verse];
for (int i=0; i<sett_lines; i++) {
    file_library[i]=read_string(i+LIB_START_VERSE);
    cout << i+1 << ". " << file_library[i] << endl;
}
string FILE_NAME;
cout << "\nFILE INDEX: ";
int file_ind;
while (!(cin >> file_ind)) {
    cout << "MISMATCH IN FILE INDEX: ";
    reset_cin();
}

函数lines_countread_string

string read_string(int verse) {
open_file(DEFAULT_SETTING);
// it just opens a file, works fine
string temp_var;
for (int i=0; i<verse; i++)
    getline(WordsFileInput, temp_var);
close_files();
return temp_var; }

int lines_count(string file_name) {
open_file(file_name);
int a=0;
string * temp_str = new string;
while (getline(WordsFileInput, *temp_str))
    ++a;
close_files();
return a; }

This is the output right before the error

这又是我的 .txt 文件的样子。

图例:

1 = 目标 -> 母亲

2 = 母亲 -> 目标

3 = 随机

变量:

变量名称:translation_direction

1

VAR 名称:show_instructions

VAR NAME:pass_threshold [%]

75

VAR 名称:generate_mistake_log

是的

文件库:

文件/日期.txt

文件/isis.txt

文件/music.txt

文件/farm.txt

文件/feminist.txt

文件/food.txt

问候

【问题讨论】:

    标签: c++ visual-studio ifstream ofstream


    【解决方案1】:
    int library_verse=sett_lines-LIB_START_VERSE;
    string *file_library=new string[library_verse];
    

    您刚刚分配了file_library 数组。 file_library 数组的大小是 sett_lines 减去 LIB_START_VERSE,不管它是什么。这就是这两行代码所说的。您没有显示 LIB_START_VERSE 的设置,但它很可能是某个大于零的正数。这一切的结果是数组的大小是LIB_START_VERSE 小于sett_lines 的值。

    for (int i=0; i<sett_lines; i++) {
        file_library[i]=read_string(i+LIB_START_VERSE);
    

    ...然后您立即开始初始化file_library 数组中的第一个sett_lines verse 条目。

    您应该能够自己找出代码中的其余错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-21
      • 2020-11-21
      • 1970-01-01
      相关资源
      最近更新 更多