Search code examples
c++freeheap-corruption

Heap corruption on free(...)


I have this enum type:

enum Cell { ALIVE='X', DEAD='O' };

And I allocate an array with it:

h_board = (Cell*) malloc(width*height*sizeof(char));

I assume I'm not doing this wrong since Cell values are chars (I'd like to stay with char sized data but I care for readability, that's why I used the enum.)

Upon free(h_board); an exception is thrown. In debugging mode I can see a heap corruption warning. I guess I'm freeing more memory than I'm allocating, but I can't see why. I also tried free((char*)h_board); trying to enforce char size deallocation, but the problem persists.

How can I fix this?


Solution

  • First of all, Cell is it's own datatype (which doesn't necessarily map to char), so use malloc with that (plus, we don't cast malloc in C):

    Cell *h_board = malloc(width * height * sizeof(Cell));
    

    Second, we need the full code to be able to help you accurately. This should run without any errors, perhaps you can build from here:

    #include <stdlib.h>
    
    int main(int argc, char **argv) {
        Cell *h_board;
    
        h_board = malloc(20 * 30 * sizeof(*h_board));
        free(h_board);
    
        return 0;
    }