I have been working on a program that keeps crashing due to segmentation fault. I cropped out the simplest part of the code causing this issue. According to what I learnt so far, if I ask the OS for memory allocation, and then use the pointer to read&write to that address of the memory, it should be good to go.
In this case, the following snipped looks pretty simple to me: opening a new file for writing, opening source file, creating outdata
to hold enough bytes, reading the exact value of bytes from source and writing to new file with fwrite
with same parameters.
Is there something fundamental I'm missing here?
int main (void)
{
FILE *outimg = fopen("test.jpg", "w");
FILE *rawFile = fopen("source.file", "r");
if(rawFile==NULL)
{
fprintf(stderr, "Unable to open source file\n");
return 1;
}
int chunkSize = 512;
int picChunkCount = 440;
unsigned char *outdata = malloc(chunkSize*picChunkCount*sizeof(unsigned char));
if(outdata==NULL)
{
fprintf(stderr,"Unable to allocate memory for *outdata\n");
return 2;
}
fread(&outdata, sizeof(unsigned char)*chunkSize*picChunkCount,1, rawFile);
fwrite(&outdata, sizeof(unsigned char)*chunkSize*picChunkCount, 1, outimg);
}