kaoD
kaoD

Reputation: 1582

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?

Upvotes: 1

Views: 1136

Answers (2)

eminemence
eminemence

Reputation: 781

It should be sizeof(Cell). Making any assumptions about the size of the enum can be dangerous. Just for your reference : What is the size of an enum in C?

Upvotes: 2

orlp
orlp

Reputation: 117661

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;
}

Upvotes: 4

Related Questions