Hi all I have trouble in allocating my memory.
I am not quit sure what's going on there and need your help.
My program is to read a file that was combined of serveral image files(called Wad file)
Each of combined image file has header :
file size: 4 bytes
file name: 28 bytes
buffer
and my code is bellow:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned int UINT4;
typedef unsigned char UCHAR;
const int file_name_length = 28;
typedef struct {
UINT4 file_size;
char file_name[file_name_length];
UCHAR *file_buffer;
} WAD; //struture of file
WAD *WadPtr; // poter of struture
int file_count;
static void readWAD(char *filename) {
int count =0,i, j=0;
FILE *fp, *out;
if (!(fp=fopen(filename,"rb"))) //read file
{
printf ("check your ass bud!\n");
exit(1);
}
if (!(out=fopen("report","wb"))) //test
{
printf ("check your ass bud!\n");
exit(1);
}
while(!feof(fp)){
WadPtr = (WAD*)realloc(WadPtr, sizeof(WAD)* (j+1)); // reallocate poniter every one image
fread((UINT4* )&WadPtr[count].file_size, sizeof(UINT4), 1, fp); // read file size
printf("File size %d: ", WadPtr[count].file_size);
if(WadPtr[count].file_size < 0) {
printf ("syzstem freaking out\n!");
exit(1);
}
fread((char* )WadPtr[count].file_name, sizeof(char), file_name_length, fp); // read file name
printf(" %s \n", WadPtr[count].file_name);
WadPtr[count].file_buffer = (UCHAR *)malloc(sizeof(UCHAR)*WadPtr[count].file_size); // read buffer
// problem is here....how should i deal with memory here?
fread((void *)WadPtr[count].file_buffer, sizeof(UCHAR), WadPtr[count].file_size, fp);
count++;
j++;
}
fwrite((void *)WadPtr[count].file_buffer, sizeof(UCHAR), WadPtr[count].file_size, out);
free(WadPtr);
if(fp != stdin)
fclose(fp);
fclose(out);
file_count=count;
}
int main (int argc, char *argv[])
{
if (argc != 2)
{
printf ("Usage: %s <File name> \n", argv[0]);
exit (1);
}
printf ("argv[1]: %s \n", argv[1]);
readWAD(argv[1]);
}
and system crashed when loop is finish
can anyone help me please!