Can you guess what will happen with the following program?
#include <stdio.h>
int main(void) {
int *count;
*count = 44;
printf("count=%d\n", *count);
return 0;
}
Actually, what does happen depends on the compiler;
in some cases it will compile, but with a warning,
and in other cases, it may compile but give a
segmentation fault when running. The reason
for this is that, when dealing with pointers
directly, it is up to the programmer to allocate
sufficient memory to store the relevant values.
This memory allocation can be done through the use of the malloc function:
#include <stdio.h>
int main(void) {
int *count;
count = (int *) malloc(sizeof(int));
*count = 44;
printf("count=%d\n", *count);
return 0;
}
The argument to malloc is the number of bytes to
allocate (in this case, the size of a single integer),
and the return value is of type void *, which
subsequently must be cast into the desired type.
One important uses of dynamically allocating memory in this way is creating arrays of a specified size during the running of a program:
#include <stdio.h>
int main(void) {
int *scores, n, i;
printf("How many scores? ");
scanf("%d", &n);
scores = (int *) malloc(n * sizeof(int));
for(i=0; i<n; i++) {
scores[i] = i;
printf("scores[%d] = %d\n", i, scores[i]);
}
free(scores);
return 0;
}
Note the use of free here to free the memory
allocated by malloc - this memory will be freed
when the program terminates, but freeing the memory
associated with variables when they will no longer
be needed is a good practice to get into.