i wrote a C (not c++) code to convert a binary image file from one format to another. i am getting a segmentation fault, and it's caused by an fwrite that i believe is pushing my pointer outside of the memory bounds that i malloc'd.
am i using the fread and fwrite properly? I assumed because i typedef 'd stuff the sizing and pointer arithmetic should be correct but i get the feeling i overlooked or am not understanding something. here is the relevant portions of code.
Code:
typedef unsigned short int type_Image;
type_Image *image;
num_subframes = 4;
/* y_size actually 512, there are 4 subframes of data concatenated */
image_size = 640 * 2048 * 2; /* x_size * y_size * bytes_per_pixel */
image = ( type_Image * ) malloc( image_size );
new_size = 640*512*2; /* x_size * y_size * bytes_per_pixel */
/*
image_size = 2,621,440
new_size = 655,360
*/
for ( f = 0; f < num_frames; f++ )
{
fread( image, image_size, 1, fp );
for ( s = 0; s < num_subframes; s++ )
{
/* split subframes into separate files */
fwrite( image + (s * new_size), new_size, 1, fp[s] );
}
}
problem is... num_subframes is 4 so s goes from 0..3.
When s == 3, the fwrite results in segmentation fault.
This is on the first time, when f == 0.
Why?