C++ 什么';我的记忆怎么了?

C++ 什么';我的记忆怎么了?,c++,memory-management,memory-leaks,C++,Memory Management,Memory Leaks,我有一个函数,它为文件大小分配了一个缓冲区 char *buffer = new char[size_of_file]; i在缓冲区上循环,并将一些指针复制到子缓冲区中,以使用较小的缓冲区单元 char *subbuffer = new char[size+1]; for (int i =0; i < size; i++) { subbuffer[i] = (buffer + cursor)[i]; } char*subbuffer=新字符[size+1]; 对于(int i=0

我有一个函数,它为文件大小分配了一个缓冲区

char *buffer = new char[size_of_file];
i在缓冲区上循环,并将一些指针复制到子缓冲区中,以使用较小的缓冲区单元

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

for (int i =0; i < size; i++) {
  subbuffer[i] = (buffer + cursor)[i];
}
char*subbuffer=新字符[size+1];
对于(int i=0;i
接下来,我调用一个函数,并将此子缓冲区和任意光标传递给它,以指定子缓冲区中的位置以及要抽象的文本的大小

  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;
}
wchar\u t*FileReader::getStringForSizeAndCursor(int32\u t大小、int游标、char*buffer){
int wlen=尺寸/2;
#如果MARKUP\u SIZEOFWCHAR==4//sizeof(wchar\u t)==4
uint32_t*dest=新uint32_t[wlen+1];
#否则
uint16_t*dest=新uint16_t[wlen+1];
#恩迪夫
char*bcpy=新字符[大小];
memcpy(bcpy,(缓冲区+光标),大小+2);
unsigned char*ptr=(unsigned char*)bcpy;//需要注意不要读取缓冲区之外的内容

对于(int i=0;i我能在你的问题代码中看到的唯一明确错误是bcpy的分配太小,你分配了一个大小为
size
的缓冲区,并立即将
size+2
字节复制到缓冲区。因为你没有使用代码中额外的2字节,只需在副本中删除+2即可

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

char *subbuffer = new char[size+1];
并将
size
字节复制到缓冲区。分配提示您正在为零终止分配额外的内存,但它不应该在那里(no+1),或者您应该分配2个字节(因为你的函数提示一个双字节字符集。不管怎样,我都看不到你以零结尾,所以把它作为以零结尾的字符串使用可能会中断


@注释中的Grizzly也有一点,为字符串和wstring分配和处理内存可能是您可以“卸载”到STL并获得良好结果的事情。

char*bcpy=new char[size];memcpy(bcpy,(缓冲区+光标),size+2)问题是C++,那么为什么你使用手动内存管理代替智能指针,而不是使用代码> char */COD>而不是<代码> STD::String ?的目标是在处理WixCARSTL时交换EndieNess;被忽略了,而且糟糕。YouUp你是正确的,我的分配和CPY被交换了。谢谢!我在撕头发。这是一个实验,来学习内存管理如何在较低的水平上工作,所以感谢处理我在C++中使用这么多C风格的垃圾。我应该开始在C,而不是这个杂乱的东西。但是我是到了,非常感谢。