2013-12-15 183 views
0

我試圖在編譯成功後在Windows 7中運行此代碼。任何想法爲什麼它崩潰?我已經給它一個隨機生成的二進制文件作爲測試的輸入,但一旦它開始,應用程序崩潰。爲什麼這個C++代碼崩潰?

#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; 
} 
+0

不要鏈接到外部頁面,包括問題中的代碼。 –

+0

你爲什麼使用'stdio'而不是'iosream'? –

+2

**從不**將字符串字面值存儲在非const char *'中。我建議使用實際的C++功能,比如'std :: string'和'std :: vector'。 – chris

回答

3

如果使用new[]你需要使用delete[],不delete。我在代碼中看到三條違規規則。

1

看起來像c代碼而不是C++。除了新的[] delete []嘗試用valgrind運行它,它很可能會告訴你所有的壞東西。