Tuesday, January 23, 2018

c - Understanding the purpose of malloc and calloc



I'm trying to get my head around C. Reading through K&R, I am flicking back and forth trying to find where it states the situations I should obtain blocks of memory dynamically.



For example, I want to have an int pointer.



int *pointer;


But then K&R states I may want to do:



int *pointer;

pointer = (int*)malloc(sizeof(int));


Essentially, what have I done here that is different? In the first case I created a pointer, that has yet to point to anything, so I guess if the computer runs out of memory and I try to point it to an int value I will have problems. The second case reserves space for my pointer. So I don't have to worry about my program having as many memory problems. Is this correct?
If this is correct, shouldn't I use malloc(or calloc) for every pointer I create? Just to make sure my program has fewer issues?


Answer



malloc is used to allocate memory. You can use a pointer by either allocating it with malloc or making it point to an already allocated portion of memory.



In the first case you have shown, unless you make pointer point to an address, it is not allocated and cannot be used. For example, you can make it point to an exiting int value:



int value = 0;
int* pointer;
pointer = &value;


But you cannot assign it to hold a value:



int value = 0;
int* pointer;
*pointer = value; // wrong because pointer is not allocated


This is what your second case is for.



calloc is basically malloc + initialization.



Edit: Regardless, this is not really a good example of the usage of malloc. The best use is probably when you need to allocate an array of variable size (not known at compile time). Then you will need to use:



int* array = (int*)malloc(N * sizeof(int));


This is useful for two reasons:




  1. If N is a variable you cannot do a static allocation like int array[N];

  2. The stack may be limited on how much space you can allocate.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...