munmap_chunk(): invalid pointer : Likely from copying a struct

41 Views Asked by At

The last line (the free) is returning a munmap_chunk(): invalid pointer error.

This is the code snippet (it's a first draft, so I'd ask you to excuse the rough-around-the-edges shape. It operates on a struct foo, which is a record (key-value pair) of rectypesize.

void csortr(foo* A, const size_t n, const int d) { // Array of foos of size n, sort by the dth char
    int count[95] = { 0 }; // Range of values guaranteed to be 95

    for (register int i = 0; i < n; ++i) {
        ++(count[index(A[i].key[d])]); // The index function gets the index for a char (independently tested. Correct)
    }

    for (register int i = 1; i < 95; ++i) {
        count[i] += count[i - 1];
    }

    foo* T = (foo*) malloc(n * rectypesize);
    memcpy(T, A, n * rectypesize);

    // This part is where I think the problem most likely is
    for (register int i = 0; i < n; ++i) {
        memcpy(&A[count[index(T[i].key[d])]], &T[i], rectypesize);
    }

    free(T);
}

The implementation is counting sort on a struct foo (of rectypesize). I know that munmap_chunk(): invalid pointer indicates a pointer being modified somewhere, but it isn't immediately apparent where.

This is called from within

void rsortr(foo* A, const size_t n) {
    // Iterate from the 'least significant' to the 'most significant' 'digit'
    for (register int i = KEYLEN - 1; i > -1; --i) {
        csortr(A, n, i);
    }
}

which is just a function call in main as:

rsortr(data, len); // data of type foo*, len a size

The index function is

short index(const char c) {
  return (short) (c - ' '); // Problem domain info: Min c = ' '; Max c = '~' => this is 0..94. Hence the 95s elsewhere
}

The struct foo is

typedef struct {
    char key[KEYLEN + 1]; // These sizes are not a part of the problem
    char value[VALLEN + 1];
} foo;

rectypesize is the constant sizeof(foo)

1

There are 1 best solutions below

2
Armali On
   // This part is where I think the problem most likely is
   for (register int i = 0; i < n; ++i) {
       memcpy(&A[count[index(T[i].key[d])]], &T[i], rectypesize);
   }

Here you think right. Whatever you may intend by this, certainly count[94] down to count[highest key index] is equal to n as a result of the preceding for loop, and storing to A[n] is of course erroneous.