Search code examples
cgccfreecalloc

free(): invalid next size (fast):


I've been struggling over this strange bug for the past hour. The code has been minimized as much as possible and I'm still getting the following error at runtime:

*** glibc detected *** ./a.out: free(): invalid next size (fast): 0x0000000001823010 ***

This is the what I'm compiling.

    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>

    void random_fill(unsigned int * to_fill, unsigned int len) {
        srand(time(NULL));
        for( unsigned int i = 0; i < len; i++) {
            to_fill[i] = (float)rand() / RAND_MAX * 100;
        }
    }


    #define SEQ_SIZE 2048
    int main(void) {
        printf("Sequence Size: %i\n", SEQ_SIZE);
        unsigned int * sequence = 0;
        sequence = (unsigned int *) calloc(0, sizeof(unsigned int) * SEQ_SIZE);

        random_fill(sequence, SEQ_SIZE);

        for(int i = 0; i < SEQ_SIZE; i++) {
            printf("%u ", sequence[i]);
        }
        printf("\n");

        free((void *)sequence);

        return 0;
    }

The command that I've been using to compile the code is gcc -std=c99 main.c and my gcc version is 4.4.7 20120313 (running on Red Hat 4.4.7). To confirm that it wasn't a bug in gcc I also compiled it with gcc 4.8.2 and still got the same error. Finally, I compiled this and ran it on my laptop and it worked worked without any issues!

Why am I getting this error? Is there something wrong with the machine or my OS?


Solution

  • As Petesh notes in the comments:

    sequence = (unsigned int *) calloc(0, sizeof(unsigned int) * SEQ_SIZE);
    

    That line will allocate 0 elements of some non-zero size. You're likely looking for:

    sequence = calloc(1, sizeof(unsigned int) * SEQ_SIZE);
    

    Which works, but doesn't fix some potential overflow issues. So you should actually write:

    sequence = calloc(SEQ_SIZE, sizeof(unsigned int));
    

    Or, even better:

    sequence = calloc(SEQ_SIZE, sizeof(*sequence));
    

    Other thoughts:

    You should only call srand() once in a given program. Normally people just call it as the first line in main().