In C, memory management begins immediately – The Craft of Coding
When you learn to program in C, more often than not people side-step the issue of memory management. It’s the one language where you really have to get a handle on the concepts of memory from day one. Sure, it is possible to write programs where you don’t have to worry about memory at all, for example the ubiquitous “Hello World” program:
#include
int main(void){
printf("hello world\n");
return 0;
}
Here memory is needed to store the string “hello world\n”, but that is done internally, similarly to how it is done in most programming languages. But the minute a program contains any sort of input, you have to start thinking about memory management. The minute a program contains a scanf()
, memory management plays a role. Here’s a simple program with a scanf()
.
#include
int main(void){
int x;
printf("integer? ");
scanf("%d", &x);
printf("%d ", x);
return 0;
}
Here the key is the use of &
in scanf()
– it allows the address of variable x
to be passed to the program, which identifies the place in memory where the information that scanf()
reads is stored. That’s a lot for the novice programmer to absorb in a very simple program. But what is the alternative? Leave out the &
, and the program fails. So the programmer has to learn from a very early stage how memory is managed. The memory concepts underpinning the use of &
could of course just be ignored, preferring instead just to use it. But that too would be a mistake – eventually a string will need to be input, with no &
required. Then the confusion will begin to set in, because the concept of memory has been ignored.
#include
int main(void){
char s[20];
printf("word? ");
scanf("%s", s);
printf("%s ", s);
return 0;
}
This is different from most programming languages where memory management foes not have to be involved in everyday housekeeping tasks like simple variable input. Dynamic arrays? Sure, why not. This is one of the issues with using C as an introductory language – the novice programmer has to concentrate too much on the intricacies of the language, rather than the broader concept of programming.
If you are learning C, learn the intricacies of memory early, and practice their implementation often.