0

Here is my code. I keep getting a segmentation fault while iterating over beginning of bufferArray[512] looking for the first jpg signature. Please help! I cant see what i've done wrong.

Im trying to design the program to deal with cases where the first jpg signature isn't in the very first 4 bytes of card.raw

int i=0;
int fileNum =0;

//open card.raw outside readjpg function
FILE* inptr = fopen("card.raw","r");
if (inptr == NULL)
{
    fprintf(stderr, "Could not create %s.\n", "card.raw");
    return 3;
}

uint8_t bufferArray[512];
FILE* outptr =NULL;
int binary=0;
fread(&bufferArray,512,1,inptr);

while(fread(&bufferArray,512,1,inptr)>0)
{
    //nested while loop is searching for first jpg signature
    while(binary==0)
    {
        if(((bufferArray[i+0])==0xff) && ((bufferArray[i+1])==0xd8) && ((bufferArray[i+2])==0xff) && (((bufferArray[i+3])==0xe0) || ((bufferArray[i+3])==0xe1)))
            binary = 1;
        else
        printf("%x",bufferArray[i]);
            i++;    
    }  

    //if condition is loking for subsequent jpg signatures
    if(((bufferArray[i+0])==0xff) && ((bufferArray[i+1])==0xd8) && ((bufferArray[i+2])==0xff) && (((bufferArray[i+3])==0xe0) || ((bufferArray[i+3])==0xe1)))
    {
        //close existing write file  if it exists
        if(outptr != NULL)
            fclose(outptr);

        //create updated fileName inside while loop
        char* fileName=NULL;
        fileNum++;
        sprintf(fileName, "%03d.jpg", fileNum-1);

        //fopen fileName
        outptr = fopen(fileName, "w");
        if (outptr == NULL)
        {
            fclose(inptr);
            fprintf(stderr, "Could not create %s.\n", fileName);

            //how might this sanity check return an error msg if it is inside a void function call? 
            //If readjpg() was an int return function, would that work the same and provide a means for sanity check?
        }

        //fwrite
        fwrite(&bufferArray,512,1,outptr);
    }    
    //this else condition is capturing all the subsequent blocks which follow the first block with jpg signature
    else 
    {
        //!!!potential bug if fread() doesn't manage to overwrite bufferArray contents like I intend it to.
        //fread
        fread(&bufferArray,512,1,inptr);

        //fwrite
        fwrite(&bufferArray,512,1,outptr);
    }  
} 
fclose(outptr);
fclose(inptr);

}

0

What happens when your "i" variable is > 512? (which it will, since you're increasing it quite a lot.

Also, you shouldn't use a char* for your filename. How are you allocating memory for it? What will happen when sprintf tries to write to a NULL pointer?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .