1

I'm having problem with vector, (in the usage of push_back) but it only appears when using additional g++ flag -O2 (I need it).

#include <cstdio>
#include <vector>

typedef std::vector<int> node;
typedef std::vector<node> graph;

int main()
{
    int n, k, a, b, sum;
    bool c;
    graph g(n, node());
    c = scanf("%i%i", &n, &k);

    for(int i=0; i<n; i++)
    {
        sum=2;
        for(int j=0; j<i; j++)
            sum*=2;
        for(int j=0; j<sum; j++)
        {
            if(j%2==0)
                c = scanf("%i", &a);
            else
            {

                c = scanf("%i", &b);
                a += b;
                g[i].push_back(a); //---------------LINE WHICH CAUSES SEGMENTATION FAULT
            }

        }
    }

    for(int i=n-2; i>=0; i--)
    {
        for(size_t j=0; j<g[i].size(); j++)
        {
            if(g[i+1][(j*2)] >= g[i+1][(j*2)+1])
                g[i][j] = g[i+1][j*2];
            else
                g[i][j] = g[i+1][(j*2)+1];
        }
    }

    printf("%i\n", g[0][0]);

    return 0;
}
user85423
  • 21
  • 3

3 Answers3

4

I think you have:

graph g(n, node());
c = scanf("%i%i", &n, &k);

in the reverse order. As it stands, the variable 'n' which you use to size graph is not initialised.

3

Initializing the vector with n before the input operation means you're invoking the dreaded Undefined Behavior. As stated here, the program is allowed to do anything after that.

Community
  • 1
  • 1
sbi
  • 219,715
  • 46
  • 258
  • 445
  • Isnt n initialized in line: c = scanf("%i%i", &n, &k); ? If not, how should I do it in this case? Thanks for help :) – user85423 Feb 13 '10 at 17:20
  • @user85423: Yes, it is (assuming scanf succeeds), but you use n *before* you do that. So I suppose sbi should have said "You don't initialize `n` before you use it" instead of "You never". – sepp2k Feb 13 '10 at 17:23
  • @sepp2k: I fixed that while you added your comment. I just didn't read the code further than the use of the uninitialized variable... – sbi Feb 14 '10 at 22:16
2

Works perfectly if you initialize n as I already mentioned in my comment. Change the first lines to:

int n, k, a, b, sum;
int c;
c = scanf("%i%i", &n, &k); // initialize n *first*
if(c != 2) return -1; // scanf does not return bool but the number of parsed arguments
graph g(n, node());
AndiDog
  • 68,631
  • 21
  • 159
  • 205