The lecturer of a C course I worked on as a TA used to show this video from Stanford CS department at the beginning of every course.just started c programming and i find this memory allocation stuff very difficult to understand...
does anyone know if there are any good resources to learn this stuff?
i'm more of a visual learned type of guy so if there are any videos or diagrams i would appreciate it.
What isn't covered on the video:
Q: When should one allocate memory dynamically instead of just creating a local variable?
A: When you want the memory to exist beyond the current function or block. Otherwise you shouldn't, because dynamic allocation complicates your code and puts you at risk of various bugs.
Q: How to avoid bugs?
A: Initialize every pointer to 0 unless you immediately call malloc on them; this results in more predictable crashes and easier debugging. Also set pointers to 0 immediately after you free() them.
Q: What's free() ?
A: You are responsible for eventually (e.g. at the end of your program) calling free() on every pointer you have gotten from malloc(); otherwise you have a memory leak. Good instructors should demand you use Valgrind or another tool which detect leaks and a ton of other memory-related bugs.
Q: How to use arrays?
A: Multiply the result of the sizeof() operator (which tells you how many bytes an individual type takes) with the size of the array to get the total byte count which you then ask from malloc(). When you have the array, either use the bracket operator to access the memory, or move the pointer by adding to it or subtracting to it.
Also, you should be aware of whether you're using C according to the C99 standard or one of the older standards. In C99 you can make a local variable-sized array without using malloc/free explicitly.