Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does fopen works without saving the returned pointer?

Tags:

c

pointers

fopen

I wrote a little program to decrypt an, OTP encrypted, file. This works just fine.

But I realized that I forgot to save the returned file pointer when calling fopen on "Solution.jpg". As you can see, I am writing to the file pointer f. I am wondering why this code is working.

#include <stdio.h>

#define FILE_SIZE 4202

int main () {
    unsigned char key[FILE_SIZE], otpCipher[FILE_SIZE];

    FILE *f = fopen("otpkey.bin", "r");
    fread(key, sizeof(char), FILE_SIZE, f);
    fclose(f);

    f = fopen("otpcipher.bin", "r");
    fread(otpCipher, sizeof(char), FILE_SIZE, f);
    fclose(f);

    fopen("Solution.jpg", "w");

    for (int j = 0; j < FILE_SIZE; ++j) {
        otpCipher[j] = otpCipher[j] ^ key[j];
        fputc(otpCipher[j], f);
    }

    fclose(f);

    return 0;
}
like image 738
johnson262 Avatar asked Feb 17 '16 10:02

johnson262


1 Answers

I just found the answer using gdb.

So since I'm using fclose() before opening the new file, the pointer to the file used before were freed. This pointer could be used again and fopen() returned this pointer every time I ran this program.

So it worked just because there were no other file opened at the time I called fopen().

This is undefined behavior and which can lead to other problems. It should be avoided in all circumstances (I did it by mistake). I just wanted to understand why this was working and fixed my code.

like image 184
johnson262 Avatar answered Nov 01 '22 11:11

johnson262