0

当我执行以下函数时出现此错误,我不知道它是什么意思。这是功能:

void readf2()
{
    std::ifstream inFile("f2",std::ios_base::binary);
    std::string str(2, '\0');
    int i = 0;
    while(inFile.read(&str[i],2)){
    cout<<"Success: ["<< i << "] = "<< (int)str[i];                        ;
    cout<<"\n";
    i++;
    }
}

该函数工作了一段时间,将各种数字写入控制台,然后由于该错误、回溯和内存映射而崩溃。这是因为我正在释放一个不存在的内存地址吗?

4

1 回答 1

1

Most likely you're giving the read call a pointer to memory that doesn't belong to you.

str[i] returns an offset in the string, but it doesn't guarantee that you have enough memory to read to that location (+2).

What you probably meant was to have an array of ints, and use the i as an index on that:

void readf2()
{
    std::ifstream inFile("f2",std::ios_base::binary);
    std::vector< int >  str; // if you're reading int's - use int, not string
    int i = 0;
    int j;
    while(inFile.read(&j,sizeof(int))){ // check what the content is here
    str.push_back(j);
    cout<<"Success: ["<< i << "] = "<< str[i];
    cout<<"\n";
    i++;
    }
}
于 2013-10-15T00:00:26.490 回答