字符指针指向字符串,然后指向字符串数组。"./a.out"中的错误:malloc():内存损坏:0x0900c3b0***

char pointer to string, then into array of strings. *** Error in `./a.out': malloc(): memory corruption: 0x0900c3b0 ***

本文关键字:字符串 malloc 错误 损坏 0x0900c3b0 内存 然后 指针 数组 out 字符      更新时间:2023-10-16

我得到这个错误:*中有错误`/a.out':malloc():内存损坏:0x0900c3b0*

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

当我执行新字符串(firstByte)时发生错误

这是代码:

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] != ''){
      //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)];

其中CCD_ 1是相当复杂的写入CCD_。

然后你尝试将一个以上的字节读入一个数组:

read(fd, firstByte, count);

注销数组的末尾,并损坏堆。

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