Miwa
Miwa

Reputation: 45

Why is the output of my buffer is not printed?

I wish you a happy new year =)

I have a behaviour I do not understand.

I try to fill a buffer with some data and when I print the buffer, nothing is print.

Here below my code :

uint8_t* buffer[50];
std::size_t pos = 0;
int cpt = 0;
while(pos < line.size())
{
   std::size_t index = line.find(str, pos);
   if(pos != std::string::npos)
   {
      string temp = line.substr(index,4);
      std::vector<uint8_t> myVector(temp.begin(), temp.end());
      uint8_t *p = &myVector[0];
      buffer[cpt] = (uint8_t*)p;
      std::cout << "Buffer[cpt] : " << buffer[cpt] << std::endl;
      cpt = cpt + 1;
    }
    pos = index + 4;
    std::cout << "buffer[0] : " << buffer[0] << std::endl;
}

for (int i=0; i < cpt; i++)
{
    std::cout << "Buffer : " <<  buffer[i] << std::endl;
}

The print of Buffer[cpt] is correct, I saw the last value I affect to the buffer But the print of buffer[0] prints nothing (Same behaviour into the print of the loop For)

Could someone knows why ? And how could I get at the end of the loop while my buffer fills correctly ?

Thank you to all.

Upvotes: 0

Views: 439

Answers (1)

lcs
lcs

Reputation: 4245

You are saving the address of the data for a vector that is then destructed. This leads to undefined behavior when you call to print buffer[0] and buffer[i] later.

If you're using vectors to begin with, why do you need the raw uint8_t* array?

{
  string temp = line.substr(index,4);
  std::vector<uint8_t> myVector(temp.begin(), temp.end());
  uint8_t *p = &myVector[0];
  buffer[cpt] = (uint8_t*)p;
  std::cout << "Buffer[cpt] : " << buffer[cpt] << std::endl;
  cpt = cpt + 1;
} // myVector is destructed here

pos = index + 4;
std::cout << "buffer[0] : " << buffer[0] << std::endl; 
// buffer[0] points to memory allocated by 
// myVector that has now been released, undefined behavor.

Upvotes: 2

Related Questions