0

I have a function that allocated a buffer for the size of a file with

char *buffer = new char[size_of_file];

The i loop over the buffer and copy some of the pointers into a subbuffer to work with smaller units of it.

char *subbuffer = new char[size+1];

for (int i =0; i < size; i++) {
  subbuffer[i] = (buffer + cursor)[i];
}

Next I call a function and pass it this subbuffer, and arbitrary cursor for a location in the subbuffer, and the size of text to be abstracted.

  wchar_t* FileReader::getStringForSizeAndCursor(int32_t size, int cursor, char *buffer) {

  int wlen = size/2;

  #if MARKUP_SIZEOFWCHAR == 4 // sizeof(wchar_t) == 4
  uint32_t *dest = new uint32_t[wlen+1];
  #else
  uint16_t *dest = new uint16_t[wlen+1];
  #endif

  char *bcpy = new char[size];
  memcpy(bcpy, (buffer + cursor), size+2);



  unsigned char *ptr = (unsigned char *)bcpy; //need to be careful not to read outside the buffer


  for(int i=0; i<wlen; i++) {
      dest[i] = (ptr[0] << 8) + ptr[1];
      ptr += 2;
  }
  //cout << "size:: " << size << " wlen:: " << wlen << " c:: " << c << "\n";

  dest[wlen] = ('\0' << 8) + '\0';
  return (wchar_t *)dest;
}

I store this in a value as the property of a struct whilst looping through the file.

My issue seems to be when I free subbuffer, and start reading the title properties of my structs by looping over an array of struct pointers, my app segfaults. GDB tells me it finished normally though, but a bunch of records that I cout are missing.

I suspect this has to do with function scope of something. I thought the memcpy in getStringForSizeAndCursor would fix the segfault since it's copying bytes outside of subbuffer before I free. Right now I would expect those to then be cleaned up by my struct deconstructor, but either things are deconstructing before I expect or some memory is still pointing to the original subbuffer, if I let subbuffer leak I get back the data I expected, but this is not a solution.

4

1 回答 1

0

我可以在您的问题代码中看到的唯一明确错误是 bcpy 的分配太小,您在其中分配了一个大小的缓冲区size并立即将字节复制size+2到缓冲区。由于您没有在代码中使用额外的 2 个字节,因此只需在副本中删除 +2。

除此之外,我只能看到一件可疑的事情,你在做;

char *subbuffer = new char[size+1];

并将字节复制size到缓冲区。分配提示您正在为零终止分配额外的内存,但它根本不应该存在(没有 +1)或者您应该分配 2 个字节(因为您的函数提示双字节字符集。无论哪种方式,我看不到你零终止它,所以将它用作零终止字符串可能会中断。

@Grizzly 在评论中也有一点,为字符串和 wstrings 分配和处理内存可能是您可以“卸载”到 STL 并获得良好结果的东西。

于 2012-10-08T16:32:47.887 回答