📓
Documents
  • Directory
  • Vancouver Cafe Database
  • Latex Resources
  • Ada Links
  • On Interviewing
  • Electrical
    • WIP - Mapping the Territory
    • Gain and Phase Margin
    • Piezoelectrics
    • Common ICs
    • WIP - PCB Design
    • WIP - High frequency circuits
      • Transmission Line Theory
      • Propogation
  • Computer Science
    • Statics, Volatiles, and Externs
    • Linked Lists
    • Dynamic Memory Allocation
    • The Stack
    • WIP - Investigations into Embedded
  • Mathematics
    • Markov Chains
      • Properties of Markov Chains
      • Cayley-Hamilton and Matrix Similarity
  • Ongoing Projects
    • Master List
Powered by GitBook
On this page

Was this helpful?

  1. Computer Science

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!

  1. calloc takes two arguments; the number of data items and the sizeof that type

  2. calloc 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.

PreviousLinked ListsNextThe Stack

Last updated 5 years ago

Was this helpful?