简体   繁体   中英

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

I get this error: * Error in `./a.out': malloc(): memory corruption: 0x0900c3b0 *

I am trying to convert a char pointer to a string, and then put that string into an array of strings for later use. I don't understand why this is not working. I am assuming that the string I put into the array gets deleted, and that might be the reason.

Error happens when I do new string(firstByte)

Here is the code:

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;**

}
}

You allocate an array large enough for a single byte:

firstByte = new char[sizeof(char)];

where sizeof(char) is a rather convoluted way of writing 1 .

Then you try to read more than one byte into that an array:

read(fd, firstByte, count);

writing off the end of the array, and corrupting the heap.

It looks like count is the wrong number of bytes to read here, since you've just used the same variable to set where in the file to seek to. You need to figure out how many bytes you actually want to read each time, and make sure you have an array large enough for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM