Free memory allocated in a different function?

前端 未结 3 1111
孤街浪徒
孤街浪徒 2021-02-01 12:05

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\

3条回答
  •  无人共我
    2021-02-01 12:38

    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).

提交回复
热议问题