C++ 指向字符串的字符指针,然后放入字符串数组。***“./a.out”中出错:malloc():内存损坏:0x0900c3b0***

C++ 指向字符串的字符指针,然后放入字符串数组。***“./a.out”中出错:malloc():内存损坏:0x0900c3b0***,c++,string,abort,C++,String,Abort,我得到这个错误: *“./a.out”中出错:malloc:内存损坏:0x0900c3b0* 我试图将一个char指针转换为一个字符串,然后将该字符串放入一个字符串数组中供以后使用。我不明白这为什么不起作用。我假设我放入数组的字符串被删除,这可能就是原因 执行新stringfirstByte时出错 代码如下: char *entries[16] = {nullptr}; string *strEntries[16] = {nullptr}; char * firstByte = 0;

我得到这个错误: *“./a.out”中出错:malloc:内存损坏:0x0900c3b0*

我试图将一个char指针转换为一个字符串,然后将该字符串放入一个字符串数组中供以后使用。我不明白这为什么不起作用。我假设我放入数组的字符串被删除,这可能就是原因

执行新stringfirstByte时出错

代码如下:

char *entries[16] = {nullptr};


string *strEntries[16] = {nullptr};
  char * firstByte = 0;
  stringstream s;
  size_t len;

  string sfB; 
  firstByte = new char[sizeof(char)];
  count = (FirstRootDirSec*512) + 32;
  lseek(fd, count, SEEK_SET); //Takes us to 32 bytes after root directory, or first entry

  //so either find a way to just read in one byte at a time, or 
  //take the first character of firstByte. firstbyte[0]. That's probably good.
  for(int i = 0; i<16; i++){
     //check first byte
     //if first byte is a 41 or 40, then it is a long directory, and then we can jump ahead 32 bytes, or 0x20


    lseek(fd, count, SEEK_SET); //Takes us to 32 bytes after
    read(fd, firstByte, count);
    count+=32;

    if(firstByte[2] != '\0'){
      //then not a long entry, and we can put it in entries.
//       string str(firstByte);


      //error happens when I do new string(firstByte)
      **entries[i] = firstByte;
      strEntries[i] = new string(firstByte);
      cout<<entries[i]<<"blah"<<endl;**

}
}

您可以分配一个足以容纳单个字节的数组:

firstByte = new char[sizeof(char)];
其中sizeofchar是一种相当复杂的写1的方式

然后尝试将多个字节读入该数组:

read(fd, firstByte, count);
注销数组的结尾,并损坏堆


看起来这里读取的字节数是错误的,因为您刚刚使用了相同的变量来设置要查找的文件中的位置。您需要计算出每次实际要读取的字节数,并确保数组足够大。

我正在尝试将字符指针转换为字符串,但您不能这样做。您可以使用const char*构造std::string。顺便说一句,这段代码太可怕了。//当我新建stringfirstByte时会发生错误-在此之前很久就发生了很多错误。停止到处使用指针。另外,您的第一个字节指向一个元素数组。我在文章中没有提到这个,但是count被用作一个标记来读取二进制文件。这只是我遍历二进制文件的方式。你认为将整个原始文件复制到缓冲区,然后处理缓冲区,而不是进出我的文件会更好吗?@Tai:不,每次读取所需的数量。这显然与文件中的当前偏移量不同,因此不要尝试对两者使用相同的变量。