Free memory allocated in a different function?

前端 未结 3 1106
孤街浪徒
孤街浪徒 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:49

    The other answers here point out the main problem -- because you dereference your apple when you call destroyEntry in main(), it passes by reference, creating a copy.

    Even once you know your problem, it helps to go back to the error and try to connect the text of what you're seeing to the problem, so that the next time it comes up you might be more likely to figure it out quickly. I find C and C++ errors can seem maddeningly ambiguous sometimes.

    Generally, when I'm having trouble freeing pointers or deleting objects, I like to print out addresses, especially right when I allocate it and right when I try to free it. valgrind already gave you the address of the bad pointer, but it helps to compare it to a good one.

    int main()
    {
      Entry * apple;
      apple = malloc(sizeof(Entry));
      printf("apple's address = %p", apple);  // Prints the address of 'apple'
      free(apple);   // You know this will work
    }
    

    After doing that, you'd notice the printf() statement gave you an address something like 0x8024712 (just making up an address in the right general range), but your valgrind output gave 0x4028E58. You'd notice they're in two very different places (in fact, "0x4..." is on the stack, not the heap where malloc() allocates from, but I'm assuming if you're just starting out that's not a red flag for you yet), so you know you're trying to free memory from the wrong place, hence "invalid free()".

    So from there you can say to yourself "Okay, somehow my pointer is getting corrupted." You already boiled down your problem to a small, compilable example, so it won't take you long to solve it from there.

    TL;DR - when running into pointer-related errors, try printing the addresses or finding them in your favorite debugger. It often at least points you in the right direction.

    None of this is to discourage posting your question on Stack Exchange, of course. Hundreds of programmers will likely benefit from your having done so.

提交回复
热议问题