Simple question. Long, complex answer.
The chief difference between the two snippets has to with the objects that get allocated and their storage durations.
In the first case, you have two objects - the unnamed int
object created by the malloc
call that stores 42
and the pointer object x
that stores the address of the int
object:
int * int
+–––+ +––––+
x: | +–+–––> | 42 |
+–––+ +––––+
The unnamed int
object that stores 42
has allocated
storage duration - it hangs around until you explicitly deallocate it with the free
library function. As written, pointer object x
has to have auto
storage duration, meaning its storage is released as soon as you exit its enclosing block or function. This is important to understand - the memory for x
is released, but the memory for the int
object it points to is not. If you lose track of the address for the dynamically allocated object, you lose the ability to deallocate it with free
. This is called a memory leak, and is generally bad juju.
In the second case, you have the single int
object x
that stores the value 42
:
int
+––––+
x: | 42 |
+––––+
If x
is declared at file scope, it has static
storage duration, meaning its storage is reserved over the lifetime of the program. If declared in the body of a function, it has auto
storage duration and its lifetime is limited to the lifetime of that function.
So, why pointers?
C requires us to use pointers in two circumstances:
Why would we ever want to use dynamically allocated memory?
when we don’t know how much memory we need until runtime;
when we need to allocate a very large object;
when we want objects to persist beyond the lifetime of any individual function, but not over the lifetime of the entire program (as opposed to items declared static
)
Pointers and dynamic memory are useful for creating any number of data structures (sometimes called containers) - lists, trees, queues, stacks, etc.
In practice, you wouldn’t use a pointer and dynamic memory as you do in your first snippet, precisely because it’s pointless. Instead, you would either be allocating an array of int
or some other type, or an element in a container like a list or tree.