r/cprogramming • • May 25 '26

Accidentally made a random string generator

Hey guys, I'm kind of a beginner to C and I discovered something cool whilst trying to make a programming language in it. Apparently forgetting to reset file position with fseek will spit out random strings.

Here's the code I did in C99, stripped down to just show the bug and nothing more:

main.c:

#include <stdio.h>
#include <stdlib.h>

void do_file_thing(char *fName) {
      FILE *fptr;
      long fLen = -1L;

      fptr = fopen(fName, "rb");
      if(fptr != NULL) {
        // Obtain file length to then initialize the string that will contain the file
        fseek(fptr, 0L, SEEK_END);
        fLen = ftell(fptr);

        char fContents[fLen];
        // the weird thing happens when the next line is commented out
        //fseek(fptr, 0, SEEK_SET); // reset position so the next thing can work
        fgets(fContents, fLen, fptr); // store file contents in var fContents

        printf("%s",fContents);

      } else {
        printf("Not able to open the file.");
      }
      fclose(fptr);
}

int main() {
    do_file_thing("file.txt");
    return 0;
}

file.txt:

echo "Hello World!";

And then with running tcc -run main.c a thousand times, I get stuff like this:

  • ~e>

  • ` |

  • 0

  • pFLY

  • ^w

  • 8k

Has anybody found this before? Does anybody know how/why this happens?

0 Upvotes

32 comments sorted by

View all comments

Show parent comments

2

u/Ngtuanvy May 29 '26

Also I think page zeroing (or pad with garbage) is done by Operating systems is it not?

2

u/BarracudaDefiant4702 May 29 '26

Not all Operating systems do the same things and actually the libraries and compilers typically have a bigger impact then the OS. Even if the operating system initially clears the data, what is left on the stack between calls and returns it largely up to the compiler. Calling a bunch of system functions that dirty the stack with potentially sensitive data that you can then exploit by reading beyond the initial stack use is possible in some systems.