Holla Tech - Learn

The malloc Function
 

The malloc() function allocates a specified number of contiguous bytes in memory.

For example: 

#include <stdlib.h>

int *ptr;
/* a block of 10 ints */
ptr = malloc(10 * sizeof(*ptr));

if (ptr != NULL) {
  *(ptr + 2) = 50;  /* assign 50 to third int */

 

malloc returns a pointer to the allocated memory.
Notice that sizeof was applied to *ptr instead of int, making the code more robust should the *ptr declaration be changed to a different data type later.


The malloc Function
 

The allocated memory is contiguous and can be treated as an array. Instead of using brackets [ ] to refer to elements, pointer arithmetic is used to traverse the array. You are advised to use + to refer to array elements. Using ++ or += changes the address stored by the pointer.

If the allocation is unsuccessful, NULL is returned. Because of this, you should include code to check for a NULL pointer.

NOTE!
A simple two-dimensional array requires (rows*columns)*sizeof(datatype) bytes of memory.

The free Function
 

The free() function is a memory management function that is called to release memory. By freeing memory, you make more available for use later in your program.

For example:

int* ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL)
  *(ptr + 2) = 50;  /* assign 50 to third int */
printf(“%d\n”, *(ptr + 2));

free(ptr); 

 


BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE C MAIN COURSE PAGE. 

C MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT