I recently learned that sometimes, when running code, the compiler(or whatever it is) ignores when there isn't enough memory for say, a string, and interacts with the string normally.
Yes, I know this is a "lucky" thing that shouldn't happen, but sometimes does.
I often find trouble when I'm trying to interact with the contents of file, as I often run out of allocated memory and I have trouble dynamically re-allocating.
To fix this, I created two functions:
- fsizeof_full <- returns the full size of the file(as if it were a string)
- fsizeof_buffer <- returns the size of the largest line in the file
So far, as I have been using these, I have not come across any problems involving segmentation faults, but I am not sure if I am just getting lucky.
Here is my code(these both have stdio.h
included):
fsizeof_full
unsigned int fsizeof_full(FILE *fp) {
unsigned int size;
while(getc(fp) != EOF)
++size;
return size;
}
fsizeof_buffer
int fsizeof_buffer(FILE *fp) {
int buff = 0; // holds the largest size of a line
int temp = 0; // holds the size of the current line
int c;
while((c = getc(fp)) != EOF) {
++temp;
if(c == '\n') {
buff = (temp > buff)?(temp):(buff);
temp = 0;
}
}
return buff;
Along with the above question("So far, as I have..."), could you possibly include more thoughts about the code regarding efficiency, necessity, etc.