0

So the problem is that this code gives malloc error when run. The input I give is n = 2, x = 4.

I think the problem is with vector pre because this happens when push_back is called.

int n, x;
cin>>n>>x;
n = (1<<n);
vector<int> taken(n, 0);
vector<int> pre;
for(int i = 1; i < n; i++) {
    if(!taken[i]) {
        taken[i] = 1;
        if(i^x < n)
            taken[(i^x)] = 1;
        pre.push_back(i);
    }
}

The error message I get is exactly this:

a.out: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) && 
old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse 
(old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)
Salmaan
  • 31
  • 8
  • I'm pretty sure that is not a compilation error. – Marshall Clow Jun 03 '19 at 23:08
  • 1
    Please provide a complete program triggering this assertion. Also, what you describe is a _runtime_ error - an assertion failure from the C library (which has malloc, which is probably used by `std::vector` under the hood. – einpoklum Jun 03 '19 at 23:08

1 Answers1

1

This line: if (i^x < n) is probably not doing what you want it to, since ^ has lower precedence than <.

You can fix that by writing if ((i^x) < n)

Marshall Clow
  • 15,972
  • 2
  • 29
  • 45