The Perils of a Container’s Reallocation

The Perils of a Container’s Reallocation

When a container reallocates its elements, their addresses change correspondingly. Consequently, the values of existing iterators are invalidated:

 #include #include using namespace std;void main() {  list  payroll;   payroll.push_back(5000.00);  list::iterator p = payroll.begin(); //p points to the first element  for (int i = 0 ; i < 10; i++) {      payroll.push_back(4500.00); //insert 10 more elements to payroll; reallocation may occur  }      // DANGEROUS  cout << "first element in payroll: "<< *p <

In this example, it may well be the case that payroll reallocated itself during the insertion of 10 additional elements, and as a result invalidated the value of p. Using an invalid iterator yields undefined behavior. It's exactly as if you were using a pointer with the address of a deleted object. To be on the safe side, you should re-assign the iterator's value:

 for (int i = 0 ; i < 10; i++) {  payroll.push_back(4500.00); //insert 10 more elements to payroll; reallocation may occur}   p = payroll.begin(); // re-assign p   cout <<"first element in payroll: "<<*p<
Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.

Sitemap