I\'m trying to learn C and I\'m currently trying to write a basic stack data structure, but I can\'t seem to get basic malloc
/free
right.
Here\
This is passing by value, which means that copy is created, thus you try to free the memory, where local variable entry
resides. Note that entry
is an object with automatic storage duration and memory where it resides will be freed automatically when your program goes out of scope of destroyEntry
function.
void destroyEntry(Entry entry)
{
Entry *entry_ptr = &entry;
free(entry_ptr);
return;
}
Your function should take a pointer (passing by reference):
void destroyEntry(Entry *entry)
{
free(entry);
}
Then instead of destroyEntry(*(apple));
you just call destroyEntry(apple);
. Note that if there is no other functionality connected with destroyEntry
function, it's redundant and it's better to just directly call free(apple)
.