MaMu
MaMu

Reputation: 1869

Bus error. Cannot access memory

I'm getting bus error.

While debugging the snippet below and stepping to the end of writeDmpFile I'm getting:

writeDmpFile (tree=0x56a310, filename=0x7fffffffd450 "20140318.221058") at unzipper_m1.c:146
146 }
(gdb) n
Cannot access memory at address 0x38353031323236

The file is written though, but program ends with bus error. Here the code:

typedef struct dmpParams_t
{
  char buff[6000000];
  size_t *size;
}dmpParams_t;

int writeFile(char *name,  unsigned char *buff, size_t *size,const char *dir )
{
  FILE * pFile;
  chdir (dir);
  pFile = fopen ( name, "wb");
  fwrite (buff , sizeof(unsigned char), *size, pFile);
  fclose (pFile);

  return 1;
}

int writeDmpFile(GTree *tree, char *filename)
{
  char dmpfilename[32];

  dmpfilename[0] ='\0';
  dmpParams_t params;
  params.buff[0]   ='\0';
  size_t size =0;
  params.size=&size ;
  g_tree_foreach(tree, (GTraverseFunc)writeDmpFileLine, &params);
  sprintf (dmpfilename, "InstrumentList_FULL.csv_%.*s", 15, filename);
  writeFile(dmpfilename,  ( unsigned char *)params.buff,  &size , dmpdir);//(size_t *)params.size, dmpdir);
}

Upvotes: 0

Views: 352

Answers (1)

David Heffernan
David Heffernan

Reputation: 613242

It looks like a buffer overrun of dmpfilename. You allocated an array of length 32. You then format it with "InstrumentList_FULL.csv_%.*s". That's 24 characters, plus 15 for the filename, plus a null terminator. That's more than 32.

Increase the size of the buffer.

Oh, and dmpParams_t is, er, rather large. Perhaps there's a stack overflow when you allocate one of those as a local.

Some other comments:

  1. You could usefully use const a bit more.
  2. Declaring size as size_t* in the struct is a bit odd. You pass the address of the struct to g_tree_foreach. I'd declare size as size_t and let g_tree_foreach modify the value.
  3. Likewise, it seems odd that you pass the address of size to writeFile. Again a const value seems to make more sense.

Upvotes: 2

Related Questions