tl;dr yes, you can use list directly, as long as while (list != NULL)
Memory leak
Yes, these two are very different. The second implementation causes a memory leak.
Memory leak is a very common bug in low level languages like c, exactly because your program "seems to work the same." In fact, you can simply do list = NULL
and the program will still work (albeit not properly). However, without calling free
, the memory occupied. In addition, you have lost track of the pointer, so it's impossible to free the memory later. This is a memory leak. If it's just a small leak, nothing bad will happen. In a large program, it will eat up your computer's RAM. You can try this by calling malloc
a bunch of times and checking the program's memory usage.
Also check out What REALLY happens when you don't free after malloc before program termination?
Your code
If you mean while (list != NULL)
instead of while (ptr != null)
then I'm pretty sure your code is correct, and you can use list
directly without ptr
(I only realized you might've made a typo after typing all the previous explanation ). The instructors might have chosen to use an extra ptr
variable for consistency with how they traverse the linked list in other functions.
But with what you have now, the code is equivalent to a single line of free(list);
. None of the elements except the first will be freed.
P.S. you can check for memory leak with gcc -fsanitize=address program.c
(does not work with mingw).