How can I implement a mechanism of some sort to prevent buffer overflows

c, file-io

Solution

Rather than using `fscanf`, you should use a combination of `fgets` and `sscanf` ... the advantage of `fgets()` is that you can specify the maximum number of bytes read, preventing buffer overflows. Secondarily, replace `sprintf` with `snprintf`.

The basic way to prevent buffer overflows is to avoid functions that write to a buffer without specifying the maximum number of bytes to write.

Problem

I am currently working on a C based log parser (making a C version of the original bash based log parser) and I was wondering how i should go about preventing a buffer overflow in the event that there is botched input, Pretty much just a way to stop the program automatically when it runs out of memory, I have provided the code below as well, thanks! ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define _GNU_SOURCE void main(int argc, char *argv[], char *envp[]) { FILE *fd; char *name; name = getenv("MCEXEC_PLAYERNAME"); char *filename; filename = malloc(sizeof "/home/minecraft/freedonia/playerdata/deathlog-.txt" - 1 + strlen(name) + 1); if (!filename) exit(EXIT_FAILURE); sprintf(filename,"/home/minecraft/freedonia/playerdata/deathlog-%s.txt",name); char buff[1024]; if ((fd = fopen(filename, "r")) != NULL) { fseek(fd, 0, SEEK_SET); while(!feof(fd)) { memset(buff, 0x00, 1024); fscanf(fd, "%[^\n]\n", buff); } printf("%s\n", buff); } else printf( "fail" ); } ``` this code below is an attempt at implementing fgets and scanf, but when i run the program it just sits there without displaying any output ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #define _GNU_SOURCE void main(int argc, char *argv[], char *envp[]) { FILE *fd; char *name; name = getenv("MCEXEC_PLAYERNAME"); char *filename; filename = malloc(sizeof "/home/minecraft/freedonia/playerdata/deathlog-.txt" - 1 + strlen(name) + 1); if (!filename) exit(EXIT_FAILURE); sprintf(filename,"/home/minecraft/freedonia/playerdata/deathlog-%s.txt",name); char *buff; buff = malloc(1024); char *finbuff; finbuff = malloc(1024); if ((fd = fopen(filename, "r")) != NULL) { fseek(fd, 0, SEEK_SET); while(!feof(fd)) { memset(buff, 0x00, 1024); memset(finbuff, 0x00, 1024); // fscanf(fd, "%[^\n]\n", buff); fgets(buff, 1024, fd); scanf(buff, "%[^\n]\n", finbuff); } printf("%s\n", finbuff); } else printf( "fail" ); } ```

Original source