我想分配一個數組大小64字節,然後遍歷數組索引從輸入文件中讀取每個字節。但是當我沒有malloc()
數組索引時,循環停留在index0中(所以每次它循環時,它都會用下一個字節替換index0中的內容,而不是將每個字節放在下一個數組索引中,並將它們全部按時間順序排列) 。無限循環fread
當我使用malloc()
它正確使用數組索引,但它是一個無限循環,並使用RAM的演出。
這裏是我的代碼:
struct BitIO {
FILE *FilePointer;
uint8_t *Buffer[64];
uint64_t BitsAvailable;
uint64_t BitsUnavailable;
} BitIO;
void Init_BitIO(const char *FileName, const char *Mode) {
BitIO.FilePointer = fopen(FileName, Mode);
malloc(sizeof(BitIO));
while (!feof(BitIO.FilePointer)) {
size_t BytesRead = 0;
for (int i = 0; i < 64; i++) {
BitIO.Buffer[i] = (uint8_t*)malloc(1);
BytesRead = fread(BitIO.Buffer[i], 1, 1, BitIO.FilePointer);
}
}
}
'的malloc(的sizeof(BitIO));'...這是一個創造性的方式來泄漏內存! – Sebivor
每次檢查內存分配或打開文件成功! – alifirat