Using free() function

This is a discussion on Using free() function within the C Programming forums, part of the General Programming Boards category; Could someone explain what is the most correct usage of free() function in this paricular case:
Code:
#include <stdio.h>
#include ...

You should only free the memory you allocate when you're all done with it. In your case, that would be after the 2nd printf, on line 37. Calling free doesn't erase the contents, but it does free up that memory to be used by something else, which may overwrite the old data, giving the effect of erasing it. Also remember, calling free doesn't change the pointer, so my_str still points to the same bit of memory, but it now contains invalid data, and trying to access it results in undefined behavior.

Some people suggest that you allocate and free strings in the same context/function, to better keep track of memory usage and reduce the likelihood of memory leaks, but that's not always possible/practical, so diligence on your part is necessary.

The other approach is to let the user specify a (dynamically allocated) buffer, and the size of that buffer. New input routines in POSIX.2008 (#define _POSIX_C_SOURCE 200809L), getline() and getdelim() use this interface:

If you look carefully, the first implementation is simpler, but uses a lot of allocations. The second implementation is a bit more complex to use, but it dynamically grows the buffer to long enough but does not use extra allocations. If you call the function often, and reuse the same buffer (like in the example main() above), this usually gives a measurable speedup.