LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   fread fwrite problem in C program, segmentation fault (https://www.linuxquestions.org/questions/programming-9/fread-fwrite-problem-in-c-program-segmentation-fault-4175521207/)

ron7000 10-06-2014 11:51 AM

fread fwrite problem in C program, segmentation fault
 
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?

linosaurusroot 10-06-2014 12:06 PM

Is fp[] actually an array of the right size [0..3] ?

ron7000 10-06-2014 12:19 PM

yeah the file pointer fp[] array is sized properly.

i figured it out. i misread my documents described how the image data is stored.
it's 2 bytes per pixel. somewhere i read the pixel data value is of type unsigned short integer, which is coincidentally 2 bytes.
I changed type_Image to "typedef char type_Image" and now things work.
I think since the original typedef of short int for type_Image is technically 2 bytes, then i say my image size is X * Y * 2, I was double bookkeeping. and i definitely would be reading in too much data eventually.


All times are GMT -5. The time now is 04:53 AM.