Bill said:
I'm beginning to see what pointers are for and it's new to me at
this
stage. Pointers in the past to me have just been another way to use
arrays. Can I have an example of malloc by itself?
Sure:
int *blk;
blk = malloc(ELEMENTS * sizeof *blk);
/* In serious program you must check the return value
of malloc before proceeding. I omitted it here because
you have previously expressed difficulty understanding code
with error checking included.
*/
Here we have called malloc to attempt an allocation of ELEMENTS*sizeof
*blk bytes of memory. ELEMENTS must be defined and set to an
appropriate value previously. After the function has succeeded you
have 'blk' pointing to a contiguous sequence of the amount of bytes of
memory you passed to malloc. By accessing them through 'blk' they are
treated as an array of ELEMENTS ints. You could've also assigned the
return value to another type of pointer (say double or unsigned char)
in which case the memory is treated as a sequence of objects of the
appropriate type. This is done automatically by your compiler.
Or is it not used
by itself?
It's often used by itself.
For what reasons would you use malloc?
Malloc is used when you need to allocate storage during runtime, i.e.,
you do not know how much memory you will need until after the program
is running (for example it might depend on user or other device input).
Statically allocated memory is out-of-question while VLA have other
drawbacks (they have a smaller scope and lifetime and they is no
portable way to detect or recover from a VLA allocation failure).
Also dynamically allocated memory persists for exactly as long as you
want, no more no less. Global objects persist throughout the program's
lifetime whether or not you want that while local objects are destroyed
when their scope is exited, and again there is nothing you can do about
that. Memory derived through malloc (or realloc or calloc) is available
until you deallocate it with free or until the program terminates.