Thread: elementary question on vector and pop_back

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    31

    elementary question on vector and pop_back

    hello,

    I have a little experience with C, and I am trying to learn C++ (brave new world for me!). I have what I am sure is a most basic question. However, I am baffled...

    Say I have the following code
    Code:
        std::vector<int> intArray;
    
        for ( i = 0; i<=10; i++ )
        {
            intArray.push_back(2*i);
            printf("%d %d %d\n",i, intArray.size(), intArray[i]);
        }
        
        printf("***********\n");
    
        for ( i = 0; i<=5; i++ )
        {
            intArray.pop_back();
            printf("%d %d\n",i, intArray.size());
        }
    this outputs what I expected after reading the vector tutorial

    Code:
    0 1 0
    1 2 2
    2 3 4
    3 4 6
    4 5 8
    5 6 10
    6 7 12
    7 8 14
    8 9 16
    9 10 18
    10 11 20
    ***********
    0 10
    1 9
    2 8
    3 7
    4 6
    5 5
    Now, the tutorial I am reading (codeguru) says "...pop_back() removes the last element in the controlled sequence. The removed element becomes invalid, and size() is decremented". I am having a problem seeing the "becomes invalid" part.

    To be explicit, can anyone tell me why the next code does not seg fault then when I add it immediately after the pop_back loop?

    Code:
        for ( i = 0; i<=10; i++ )
        {
            printf("%d %d %d\n",i, intArray.size(), intArray[i]);
        }
    I get

    Code:
    0 5 0
    1 5 2
    2 5 4
    3 5 6
    4 5 8
    5 5 10
    6 5 12
    7 5 14
    8 5 16
    9 5 18
    10 5 20
    Thank you very much.

    mc61

  2. #2
    Registered User
    Join Date
    Jan 2007
    Posts
    330
    because it is undefined what happens when you access elements after they are removed. It can seem to work on some compilers but can crash on others. MSVC2008 throws an exception with your code

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    31
    Thanks,

    Indeed, after I submitted my post I found the answer a few threads earlier (and I did search for it before posting...).

    Sorry for the bandwidth, and thanks for the help.

    mc61

  4. #4
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Yes -- it's called "undefined behavior," not "crashing behavior." What could possibly happen is, officially, the set of all things. A crash is something

Popular pages Recent additions subscribe to a feed