Dynamic Memory Allocation :: malloc(3), calloc(3), bzero(3), memset(3)
- The prototype for
malloc(3)is:void *malloc(size_t size);
malloctakes in asize_tand returns a void pointer. Why does it return a void pointer? Because it doesn't matter to malloc to what type this memory will be used for. - Let's see an example of how
mallocis used:int *ip;
Pretty simplistic.
ip = malloc(5 * sizeof(int));
/* .. OR .. */
ip = malloc(5 * sizeof(ip));sizeof(int)returns the sizeof an integer on the machine, multiply by 5 and malloc that many bytes. The second malloc works because it sends what ip is pointing to, which is an int. - Wait... we're forgetting something. AH! We didn't check for return values. Here's some modified code:
#define INITIAL_ARRAY_SIZE 5
Now our program properly prints an error message and exits gracefully if malloc fails.
/* ... code ... */
int *ip;
if ((ip = malloc(INITIAL_ARRAY_SIZE * sizeof(int))) == NULL) {
(void)fprintf(stderr, "ERROR: Malloc failed");
(void)exit(EXIT_FAILURE); /* or return EXIT_FAILURE; */
} calloc(3)works like malloc, but initializes the memory to zero if possible. The prototype is:void *calloc(size_t nmemb, size_t size);
Refer to Weiss pg. 164 for more information oncalloc.bzero(3)fills the first n bytes of the pointer to zero. Prototype:void bzero(void *s, size_t n);
If you need to set the value to some other value (or just as a general alternative to bzero), you can use memset:void *memset(void *s, int c, size_t n);
where you can specify c as the value to fill for n bytes of pointer s.