0

I have a small, but annoying, problem here.

So here are my structures.

typedef struct tElem {
    struct tElem *ptr;
    int data;
} *tElemPtr;


typedef struct {
    tElemPtr Act;
    tElemPtr First;
} tList;

And here is the allocation. This is where the heap corruption occurs.

tElemPtr newElemPtr = (tElemPtr)malloc(sizeof(tElemPtr));
.
.
.
free(newElemPtr);

But it doesn't occur, when I use size of the actual structure.

tElemPtr newElemPtr = (tElemPtr)malloc(sizeof(struct tElem));
.
.
.
free(newElemPtr);

Could somebody please explain to me, what am I missing here?

Thank you.

  • Show your code. – Sean F Oct 03 '20 at 21:11
  • 2
    `sizeof(tElemPtr)` is the size of a _pointer_ to `struct tElem` and _not_ the size of the struct itself [because `tElemPtr` is a typedef for: `struct tElem *`]. You need to allocate enough space to contain the `struct` and _not_ just a pointer to it, hence, using `sizeof(struct tElem)` is what works (i.e. it's [probably] 16 bytes vs 4/8 bytes for the pointer). – Craig Estey Oct 03 '20 at 21:13
  • 2
    @dxiv But, don't cast `malloc` ... https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Craig Estey Oct 03 '20 at 21:24
  • @CraigEstey Right, of course. That should have been just `tElemPtr newElemPtr = malloc(sizeof(*newElemPtr));`. – dxiv Oct 03 '20 at 21:27

1 Answers1

1

It's because you are mallocing a pointer not a new struct

sizeof(tElemPtr) is going to return the size of a pointer not the size of the struct.

shrewmouse
  • 5,338
  • 3
  • 38
  • 43