I observed in a walkthrough video in Week 4 (structs-0, I believe) David mentions that any variable created with GetString() should be free()d after its usage, due to the fact that, I vaguely quote from memory, "GetString() does indeed use malloc()" and thus returns a memory address.

Week 4 introduces the first instances of dynamic memory allocation and its related functions, malloc() and free(). Bearing this in mind, does that mean that every instance of GetString() in our programs prior to Week 4, such as in vigenere.c, creates a variable that has been dynamically allocated? Furthermore, does that mean we have been unwittingly creating memory leaks in our programs, seeing as we were not instructed to use free() at this stage?

I keep my completed problem sets on my own system, and I'm sure it's relatively harmless (considering that the programs do not run for very long), but I was musing on this newfound knowledge. Should I append the problem sets and free any dynamically allocated variables?


Yes it's true that for simplicity's sake, in the first psets, we din't free() the strings allocated by GetString() and that caused memory leaks.

Nevertheless, most modern operating systems can see when a program exists with memory leaks, and frees the memory itself. So even if you run your program a million times you would not notice any memory shortage (probably).

But of course, if you want to be thorough, feel free to go back to those psets and free the memory allocated by GetString(). If you feel that need I would say it's a good sign that it will make you a good programmer (at least specifically at memory management.)

Hope this helps! Happy Coding! :)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .