3

I'm trying to implement a radix sort, and this code produce a memory failure:

(free(): invalid next size (fast))

The code is the following:

unsigned int * radix(unsigned int *x,int n, int g,bool verbose)
{
    int elem_size = sizeof(unsigned int)*8;
    int mask = ((1<<g)-1);    
    float num_rounds= ((float)elem_size/(float)g);
    int B = 1 << g; // 2^g BTW

    vector<unsigned int> buckets[B];

    // begin radix sort
    for( unsigned int round=0 ; round<num_rounds ; ++round)
      {

        // count
        for(int elem=0 ; elem<n ; ++elem)
        {
            // calculate the bucket number:
            unsigned int const bucket_num = ( x[elem] >> g*round) & mask;
    --->        buckets[bucket_num].push_back(x[elem]);
        }
        // more stuff
    }
    return x;
}

GDB states that the error is inside push_back, but elem is always smaller than n (where n is the size of x[]). So, I thought that it could only be on bucket_num. However, just before it crashes GDB gives me their values:

Breakpoint 1, radix (x=0x604010, n=50, g=4, verbose=true)
    at radix.mpi.seq.cpp:38
38                buckets[bucket_num].push_back(x[elem]);
2: B = 16
1: bucket_num = 2

any ideas?

D Stanley
  • 149,601
  • 11
  • 178
  • 240
RSFalcon7
  • 2,241
  • 6
  • 34
  • 55
  • 1
    is `//more stuff` actual code? You need to include all of the code. Just because the crash was on a line, does not mean that's where the problem is. – SoapBox May 14 '12 at 19:22
  • //more stuff was code, but I comment and the error remain – RSFalcon7 May 14 '12 at 19:35
  • I have no idea why, but I changed the memory allocator from 'new unsigned int(n)' to 'malloc((n*sizeof(unsigned int))' and it works just fine. Any reasonable explanation? – RSFalcon7 May 14 '12 at 19:38
  • 3
    @RSF Neither line appears in your original question. It's hard to diagnose problems in code you haven't shown us. (Aside: I don't think `new unsigned int(n)` means what you think it does.) – Alan Stokes May 14 '12 at 19:41
  • @AlanStokes ya! you are right! haste is the enemy of perfection... – RSFalcon7 May 14 '12 at 19:49
  • possible duplicate of [C++ Error: free(): invalid next size (fast):](http://stackoverflow.com/questions/4729395/c-error-free-invalid-next-size-fast) – Bo Persson May 14 '12 at 22:45

1 Answers1

4

From your comment, it's clear that: accessing unsigned int *x is the reason for the invalid write error you get when you access it in your radix function.

unsigned int *x = new unsigned int(n); allocates a single unsigned int and assigns the value n to it. You really wanted an array of unsigned ints: unsigned int *x = new unsigned int[n];

In general, running through Valgrind helps find memory leaks and where exactly the problem lies. Because, often the error message you get hardly happens at a line where it appears to happen.

P.P
  • 117,907
  • 20
  • 175
  • 238