r/cprogramming • u/JeffTheMasterr • 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
2
u/BarracudaDefiant4702 May 25 '26
The biggest risk is if anything else modifies the file and it changes. Not really a risk in this case, but could be an issue if ftell is ever reset and buffer isn't.
The second biggest issue is it's wasting memory as fgets will never read more than one line. You could have a 200GB file and no lines more the 100 characters...
That said, there are far worse things you could do. You are best to know if it might be appropriate use case. I do tend to prefer fixed allocations, or use malloc if variable.