为什么这个C ++代码会崩溃?

时间:2013-12-15 19:33:14

标签: c++

我正在尝试在成功编译后在Windows 7中运行此代码。有关崩溃原因的任何想法?我已经给它一个随机生成的二进制文件作为测试输入,但是一旦它开始,应用程序崩溃。

#include <cstdio>
#include <cstdint>
using namespace std;

long getFileSize(FILE *file) {
        long currentPosition, endPosition;
        currentPosition = ftell(file);
        fseek(file, 0, 2);
        endPosition = ftell(file);
        fseek(file, currentPosition, 0);
        return endPosition;
}

struct frame {
        uint8_t bytes[535];
};

struct spectralFrame {
        uint8_t bytes[512];
};

struct spectralFrameWord {
        uint16_t words[256];
};

int main() {
        char *filePath = "C:\\Payload\\Untitled.bin";
        uint8_t *fileBuffer;
        FILE *file = NULL;
        file = fopen(filePath, "rb");
/*      if((file = fopen(filePath, "rb")) == NULL)
                cout << "Failure." << endl;
        else
                cout << "Success." << endl;
*/
        long fileSize = getFileSize(file);
        fileBuffer = new uint8_t[fileSize];
        fread(fileBuffer, fileSize, 1, file);
        fclose (file);
        long frameCount = fileSize / 535;
        frame *frames = new frame[frameCount];
        for(int i = 0, j = 0, k = 0; i < fileSize; i++) {
                frames[j].bytes[k++] = fileBuffer[i];
                if((i % 534) == 0) {
                        j++;
                        k = 0;
                }
        }
        delete fileBuffer;
        fileBuffer = NULL;
        spectralFrame *spectralFrames = new spectralFrame[frameCount];
        for(int i = 0; i < frameCount; i++) {
                for(int j = 22, k = 0; j < 534; j++) {
                        spectralFrames[i].bytes[k++] = frames[i].bytes[j];
                }
        }
        delete frames;
        frames = NULL;
        spectralFrameWord *spectralFrameWords = new spectralFrameWord[frameCount];
        uint16_t word;
        for(int i = 0; i < frameCount; i++) {
                for(int j = 0, k = 0; i < 511;) {
                        word = spectralFrames[i].bytes[j++] << 8;
                        spectralFrameWords[i].words[k++] = word | spectralFrames[i].bytes[j++];
                }
        }
        delete spectralFrames;
        spectralFrames = NULL;
        filePath = "C:\\Payload\\Untitled.tsv";
        file = fopen(filePath, "w");
/*      if((file = fopen(filePath, "w")) == NULL)
                cout << "Failure." << endl;
        else
                cout << "Success." << endl;
*/
        for(int i = 0; i < 256; i++) {
                fprintf (file, "%u\t%u\n", i, spectralFrameWords[0].words[i]);
        }
        fclose (file);
        return 0;
}

2 个答案:

答案 0 :(得分:3)

如果您使用new[],则需要使用delete[],而不是delete。我在您的代码中看到三条违反此规则的内容。

答案 1 :(得分:1)

看起来像c代码而不是c ++。除了new [] delete []尝试使用valgrind运行它之外,它很可能会显示你所有的坏东西。