简体   繁体   中英

C++ Segmentation fault with vector

In below code, I'm trying to display Daily Report with the total Sale. Output is correct but exit with segmentation fault. How do I solve this pls?

Output is

Date        Total Sales
03Nov13     745
13Jan14     538
Segmentation fault (core dumped)

Code:

for (int index=0;index<stockVector.size();index++)
    {                
            if ( stockVector[index].getTransDate() == stockVector[index+1].getTransDate())
            {
                int totalSum = ((stockVector[index].getQtyPurchase() * stockVector[index].getUnitPrice()) +
                        (stockVector[index+1].getQtyPurchase() * stockVector[index+1].getUnitPrice()));                 
                cout << stockVector[index].getTransDate() << "\t\t" << totalSum << endl;
            }
        }

This is my data in text file which has been stored in vector.

ProductID:Description:Price:Qty:Transaction Date

003:Calendar:5:104:03Nov13
079:Revlon Foundation:5:45:03Nov13
005:MacBook Pro:3500:1:10Jan14
010:NesCafe Latte:1:9:1Jan14
095:Lipton Tea:5:95:13Jan14
096:Milk Tea:3:21:13Jan14
066:Samsung Note 3:450:1:23Jan14
088:HP Mouse:23:100:24Jan14

In your loop, you're using an index ( index+1 in the condition) that can reference an element beyond the last element of the vector (when index reaches stockVector.size() - 1 ). Dereferencing a pointer (which stockVector does when its operator[] is called) at a location beyond the end of an array is undefined behaviour, so anything can happen (including getting a correct result and then crashing).

To solve this, simply clamp the loop to stockVector.size() - 1 :

for (int index=0;index<stockVector.size() - 1;index++)
{
    // ...

You may however have to evaluate whether this solution is adequate for the last element of your vector.

stockVector[index+1]

That will obviously go past the end of the vector when index reaches size() - 1 .

If you need to peek at the next element you will need to verify that you don't go past the end of the vector and you will also need to figure out what to do when you reach the last element and/or have an odd number of elements.

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