Think about a program that need sometime (not allways) an array of 1000 integers.
Normaly you declare an array:
Code:
int main () {
int array[1000];
…
// work with the array or not
…
return EXIT_SUCCESS;
}
This code reserve allways memory on the stack for the array.
It doesn't matter if you need it or not.
Now the same with malloc:
Code:
int main () {
int *array = NULL;
…
// if we need the array …
if (array == NULL) {
array = malloc(1000 * sizeof(*array));
if (array == NULL) {
fprintf(stderr, "Ooops, no memory left.\n");
return EXIT_FAILURE;
}
// you can use it as a normal array like
// array[0] = 42;
// the indexes goes from 0 to 999 in this example
…
// at the end, we should free it
free(array);
array = NULL;
}
…
return EXIT_SUCCESS;
}
In this example, there is only a pointer on the stack that needs less bytes.
You only allocate memory if you need it.