XOpt 6
XOpt 6

Reputation: 11

How do I solve "realloc(): invalid next size" error?

Here is the section of code where my program crashes:

if (fromNode != toNode) {
    pthread_mutex_lock(&mtxs[fromNode]);
    g->out[fromNode]++;
    if (g->in[toNode].index == g->in[toNode].size) { 
        g->in[toNode].size += 100;
        //printf("Thread:%d, Resizing array of incoming nodes for node %d, size:%d\n", threadID, toNode+1, g->in[toNode].size);
        g->in[toNode].nodes = (int *)realloc(g->in[toNode].nodes, g->in[toNode].size * sizeof(int));
        if (g->in[toNode].nodes == NULL) {
            printf("Memory allocation failed\n");
            exit(1);
        }
    }
    sortedInsert(g, fromNode, toNode); 
    pthread_mutex_unlock(&mtxs[fromNode]);
}

This code is in a loop in a function, run by many threads which reads from a buffer the variables fromNode and toNode and puts them in a struct. The buffer is filled with data read from a file. When I run this with a small file, everything goes fine. Now I tried with a 15 million-data file, and the program crashed. The errors vary between executions and are:

mremap_chunk(): invalid pointer Aborted (core dumped)

or

corrupted double-linked list Aborted (core dumped)

or

corrupted size vs. prev_size Aborted (core dumped)

But it always crashes on the realloc after tot milion of iterations. I tried to run it with Vallgrind

valgrind --tool=memcheck --leak-check=full -s ./prog

but for some reason it doesn't crash, the output is correct, and valgrind doesn't find any memory leaks or errors.

Maybe the problem is that the size gets too big, and it fills the heap, but why does it work when I run it with valgrind? And how can I solve it?

Upvotes: 0

Views: 77

Answers (0)

Related Questions