How can I implement any mechanism to prevent buffer overflows

I'm currently working on a C-based log parser (creating a C version of bash-based source parsing), and I was wondering how I should go about preventing buffer overflows in the event of input failure. Pretty much just a way to stop the program automatically. when she runs out of memory, I also provided the code below, 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 to implement fgets and scanf, but when I run the program, it just sits there without outputting 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" );
}
+3
source share
2 answers

fscanf fgets sscanf... fgets() , , . -, sprintf snprintf.

, .

+5

@Jason.

fgets(), , (.. ). sscanf() , , .

.

fgets and sscanf

+1
source

All Articles