I'm working with a C program that reads from a single file and uses `sprintf` to write that data into multiple files, I'm going wrong somewhere, but I don't really know where and that results in this error:

> 
> `*** stack smashing detected ***`
> 
> 
> 

The code usable for reproduction is given here:

```
FILE * source=fopen("card.raw","r");// defines source I will read from

char array[512];
int active_read=0;
char * filename;
sprintf(filename, "%03i.jpg",i);
FILE *image=fopen(filename, "a"); //my understanding of sprintf to create a file

while(fread(array,sizeof(char *),512,source)==512) // if 512 characters can be detected
{
    if(array[0]==0xff && array[1]==0xd8 && array[2]==0xff && (array[3] & 0xf0==0))
    {
        if(active_read==1)
            fclose(image);
        active_read=1;
        sprintf(filename, "%03i.jpg",i);
        image=fopen(filename, "a");
        fwrite(array, sizeof(char *),512, image);
        i++;
    }
    else if(active_read==1)
        fwrite(array, sizeof(char *), 512, image);
}

```

I rand the code with my debugger(CS50 Debugger). And I found that the `if` condition is never even checked. It jumps from the `while` loop to the `else if` condition, never does anything and then leaves with the error.