在push_back上的STL矢量崩溃

时间:2014-03-14 19:01:23

标签: c++ file vector stl

我正在编写一个需要操作位数组的简单程序。使用ifstream从文件加载数组;我只是从文件中读取字节,直到我点击EOF,将每个完整的数组推到矢量上。

我看到的崩溃是一致的:第7次对向量的push_back调用失败,仅在Release版本中。在Debug中,相比之下,我们可以无限期地读取数组,而不会遇到EOF。这似乎意味着某种记忆搞砸了,但我没有看到任何我明显做错的事情。无论数组的大小如何,无论我是否真正从文件中读取任何内容,都会发生崩溃。

有一点需要注意:我在这里工作的是一个提供文字零文档的库。以前的开发人员必须通过从DLL转储字符串并进行大量实验来对API进行逆向工程(坦率地说,我很惊讶我们有一些可行的东西)。所以我愿意接受一个可能的解释:“你正在使用的那个图书馆有你的堆栈”,缺乏更好的想法。

无论如何,这是代码:

std::vector<char*> bufList;
// Grab new buffer information from the file bufFilename.
void loadBuffers(int bufWidth, int bufHeight) {
    printf("Reloading buffers...\n");
    // First destroy old buffers, if applicable.
    if (!bufList.empty()) {
            for (std::vector<char*>::iterator i = bufList.begin(); i != bufList.end(); ++i) {
                    free(*i);
            }
    }
    bufList.clear();

    printf("bufList is empty now\n");

    // Read buffers from the file until we hit the end. Assume the file is properly formatted!
    // Also assume there is at least one buffer in the file.
    ifstream handle(bufFilename, ios::in | ios::binary);
    char* curBuffer;
    int numBuffers = 0;
    // One bit per pixel, ergo 8 pixels per byte.
    // NB implicit assumption that width * height is cleanly divisible by 8!
    int bufBytes = bufWidth * bufHeight / 8;
    printf("Each buffer needs %d bytes\n", bufBytes);
    while (TRUE) {
            printf("Loading buffer %d\n", numBuffers);
            // Allocate space for a new buffer.
            curBuffer = (char*) malloc(bufBytes);
            printf("Allocated buffer\n");
            // Read one buffer's worth of data from the handle.
            handle.read(curBuffer, bufBytes);
            printf("Read complete\n");
            // Assume if we hit EOF that there's no valid buffer.
            if (handle.eof()) {
                    printf("Hit EOF; free and break\n");
                    free(curBuffer);
                    break;
            }
            printf("Not done yet!\n");
            // Add the new buffer to the bufList.
            bufList.push_back(curBuffer);
            printf("Added buffer to vector; now are %d elements in vector.\n", bufList.size());
            numBuffers++;
    }
    handle.close();
    printf("Loaded %d buffers\n", numBuffers);
}

0 个答案:

没有答案