3

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" );
}
4

2 回答 2

5

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.

于 2012-05-10T15:29:47.037 回答
1

我同意@Jason。

您可以使用 fgets() 将一行文本放入字符数组中,该数组将以空字符结尾(即:字符串)。然后,您可以使用 sscanf() 来解析每一行,假设每一行文本都有严格的格式。

以下帖子也可能会有所帮助。

fgets 和 sscanf

于 2012-05-10T16:16:11.043 回答