I wanted to try using malloc and a BUFFER structure of 512BYTES for this exercise with the intention of creating a file if the 4 signatures of a JPG are detected and fwriting the struct of 512B into the new file, fwriting the struct into a preexisting file if the 4 signatures of a JPG are not detected, or simply freeing the struct if a file does not exist. However, I just get 50 corrupted or grey images based on whether I use
(access( title, F_OK ) != -1) or
if(outptr != NULL) (not used in my code at the moment) for my file existence checking, but no matter what no correct images. What am I doing wrong? Also, just a question regarding malloc and free. Everytime I free buf, I have to do
buf = malloc(sizeof(BUFFER)) again which is why it is at the bottom of my loop else I get a double free error. Is it because once I free buf, both the allocated space of 512 BYTES and the 512 previously stored bytes are discarded meaning buf is back to pointing at nothing? What happens if I do not malloc again and I fread with buf? Where do the 512 read bytes go since I did not encounter a segmentation fault error but rather a double free error.