I have this struct
as part of a program along with it's create and destroy functions. However when I try to free a struct
instance the program crashes from a free
-related error, for example the main
function would crash with munmap_chunk(): invalid pointer
I don't understand why the pointers are invalid.
p.s.: What would be the best way to initialize new
in euCreate()
? Everything I try either causes a memory leak or doesn't work.
Eu euCreate()
{
Eu new = malloc(sizeof(new));
(*new).Judges = malloc(sizeof(Judge) * 2);
(*new).Jlen = 2;
(*new).Jidx = 0;
(*new).States = malloc(sizeof(State) * 2);
(*new).Slen = 2;
(*new).Sidx = 0;
return new;
}
void euDestroy(Eu eu)
{
free(eu->Judges);
free(eu->States);
}
int main()
{
Eu eu = euCreate();
euDestroy(eu);
}
typedef struct eu{
struct judge* Judges;
int Jlen;
int Jidx;
struct state* States;
int Slen;
int Sidx;
}* Eu;
You're not allocating enough space for your structure:
Eu new = malloc(sizeof(new));
sizeof(new)
gives you the size of a pointer, not what it points to. So when you subsequently assign values to members of the struct, you write past the bounds of allocated memory. This invokes undefined behavior, which in this case causes your code to crash.
Allocate space for what the pointer points to.
Eu new = malloc(sizeof(*new));
Also, it's bad practice to typedef a pointer, as it obscures the fact that you're working with a pointer. Better to just typedef the struct and explicitly use the pointers in each declaration where needed.