Well, I have a strange problem with files. Basically what I'm trying to do is open 2 24-bit bmp files, compare their pixels, and write back out the pixels that remain the same and yellow pixels where they differ. This worked perfectly fine when I streamed the two files, but now I want to load the first file entirely into memory, and stream the second file. So I wrote the code to do this, and ran it, and oddly enough, a couple of the pixels wound up as strange offshoots of their original pixel, usually replacing one of the 3 color channels with 255. I suspect this to be a problem with overwriting memory, but can't for the life of me figure it out.
Here's my code:
Code:
#include <stdio.h>
//RGB pixel structure
typedef struct {
unsigned char c[3];
} tCol;
int main(int argc, char **argv) {
FILE *f1, *f2, *t;
tCol c1[480000], c2;
unsigned char b[54];
int n, s;
f1 = fopen(argv[1],"rb");
f2 = fopen(argv[2],"rb");
t = fopen(argv[3],"wb");
//skip header information
fseek(f2,54,SEEK_SET);
fread(b,54,1,f1);
fwrite(b,54,1,t);
s = fread(c1,3,480000,f1); //read file1 into buffer
n = 0;
while (fread(c2.c,3,1,f2) > 0) { //read file2 in pixel at a time
if ((c1[n].c[0] != c2.c[0]) || (c1[n].c[1] != c2.c[1]) || (c1[n].c[2] != c2.c[2])) { //if pixel differs
c1[n].c[0] = 0; //overwrite pixel in buffer with yellow
c1[n].c[1] = 255;
c1[n].c[2] = 255;
}
n++;
}
fwrite(c1,3,s,t); //flush buffer to file
//if not an even 32 bits, add 0's to make it
b[0] = 0;
b[1] = 0;
b[2] = 0;
fwrite(b,s % 4,1,t);
fclose(t);
fclose(f1);
fclose(f2);
}
The images will never exceed 800x600, thus why I have hard coded in 480000.
The image turns out perfect for an 800x600 image, but when I plug in a 54x32 image, a few pixels will suddenly go green, red, purple, blue, or teal when they're not supposed to, and usually they are to the left and right of or on an area that was supposed to turn yellow.