Dynamic Memory Allocation
An Example of DMA in C
// Implementation of the malloc function to create an int array
int* i = (int*) malloc( 10 * sizeof(int));
if (i==NULL){
printf("ERROR: unsuccessful allocation\n");
return -1; // End the proram
}
// Accessing this array through pointer arithmetic
*(i + 1) = 3; // Store the number 3 in the 2nd position
printf("%d", i + 0); // Print the address of the 1st int
printf("%d", *(i)); // Print the value of the 1st int
// Accessing this array through array syntax
i[1] = 3; // Store the number 3 in the 2nd position
printf("%d", &i[0]); // Print the address of the 1st int
printf("%d", i[0]); // Print the value of the 1st int
// Free up the allocated space in memory
free(i);
i = NULL; // Make sure the i pointer is not left hanging!
calloc
is extremely similar to malloc
with two key differences!
calloc
takes two arguments; the number of data items and thesizeof
that typecalloc
initializes the relevant memory locations to zero
Calling free
is extremely important because it lets the memory manager know that the freed locations are garbage and can be removed as such. Without free
the heap of a program will continuosly fill up with garbage until there is no more space left.
It is important to write pointer=NULL after calling free(pointer) so as not to leave the pointer hanging. A hanging pointer will return garbage values and may create unexpected program results if your program tries to access the pointer at a later time.
Last updated
Was this helpful?