ollydbg
ollydbg

Reputation: 3525

When to rely on garbage collection and when not?

If I'm going to do this kinda operation many times:

  res = mysql_perform_query(conn, "show tables");

  printf("MySQL Tables in mysql database:\n");
  while ((row = mysql_fetch_row(res)) !=NULL)
      printf("%s\n", row[0]);

Do I need to run mysql_free_result(res); at the end of each operation or rely on garbage collection mechanism , why?

UPDATE

I still don't see clearly how to judge whether some data structure needs to clean up according to existing answer.

Upvotes: 0

Views: 233

Answers (1)

Mauricio
Mauricio

Reputation: 1711

In C++, never. C++ is not garbage-collected. The closest would be RAII, which is basically wrapping stuff that needs cleanup in objects that do said cleanup in their destructor. I can't give further detail since I don't really use C++ all that much.

As an aside: Even in a GC'd language, GC only works well for memory. Explicit cleanup's still needed for stuff like SQL connections, file handles, etc.

Bottom Line: You always have to clean up once you're done. (Unless the documentation says it's not needed)

Upvotes: 2

Related Questions