My task is to read a yuv file and to each component(Y,Cb,Cr) of it, I'm appending some data and storing it into another file. I have tried the below code:
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fp=fopen("traffic_1920x1080.yuv","rb");
FILE *myYUV=fopen("traffic_1920x1088.yuv","ab");
int count=0;
unsigned char *y=(unsigned char*)malloc(sizeof(unsigned char)*1920*1080);
unsigned char *u=(unsigned char*)malloc(sizeof(unsigned char)*(1920/2)*(1080/2));
unsigned char *v=(unsigned char*)malloc(sizeof(unsigned char)*(1920/2)*(1080/2));
unsigned char ypad[1920*8];
unsigned char upad[(1920/2)*4];
unsigned char vpad[(1920/2)*4];
for(int i=0;i<(1920/2)*4;i++)
{
ypad[i]=255;
upad[i]=128;
vpad[i]=128;
}
for(int i=(1920/2)*4;i<1920*8;i++)
ypad[i]=255;
while (!feof(fp))
{
fread(y,sizeof(unsigned char),1920*1080,fp);
fread(u,sizeof(unsigned char),1920/2*1080/2,fp);
fread(v,sizeof(unsigned char),1920/2*1080/2,fp);
fwrite(y, sizeof(unsigned char),1920*1080,myYUV);
fwrite(ypad,sizeof(unsigned char),1920*8,myYUV);
fwrite(u,sizeof(unsigned char),1920/2*1080/2,myYUV);
fwrite(upad,sizeof(unsigned char),1920/2*4,myYUV);
fwrite(v,sizeof(unsigned char),1920/2*1080/2,myYUV);
fwrite(vpad,sizeof(unsigned char),1920/2*4,myYUV);
printf("Frame %d created\r",count);
y+=1920*1080;
u+=1920/2*1080/2;
v+=1920/2*1080/2;
count ++;
}
free(y);
free(u);
free(v);
fclose(fp);
fclose(myYUV);
}
Howevr the above code works fine for the first loop, but in the second loop i get an exception
Access violation writing location 0x0092f000.
at line fwrite(y, sizeof(unsigned char),1920*1080,myYUV);
Is this a problem in pointer increment? or it is something else? Please reply. Thanks in advance.
These increments:
y+=1920*1080;
u+=1920/2*1080/2;
v+=1920/2*1080/2;
will increment the pointers past the end of the allocated memory. For example, y
points to the start of 1920*1080 bytes of allocated memory. Increasing it by that much makes it point past the end of that memory. This results in reading/writing to/from unallocated memory. That's why you get an access violation.
I don't actually see a reason for those pointers to be incremented at all.
Other than that, your code should check for error conditions (did fopen() succeed, etc.)