stdlib.h: The heap

Introduction

Introduction

variable length array using the heap or the stack

void my_function(int n){
    float vals[n];
    return process(n, vals);
}

stack approach above. deleted when function ends

void my_function(int n){
    [something using malloc]
}

heap memory: allocated at run time needs to be manually removed

stack overflow + stack hits point reserved for heap?

+ memory leaks

space for stack limitated with need to reserve space to prevent overlapping with heap heap in c doesn’t mean data structure. heap as in pile, or pool, just a description. just synonym for pile, area etc. Heap in c. Allocate with malloc?

malloc

malloc (memory allocation):

int * ptr = (int *) malloc(10 * sizeof(int));

calloc

calloc (contiguous allocation):

int * ptr = (int *) calloc(10, sizeof(int));

calloc initiates all to 0

free

can free

int * ptr = (int *) malloc(10 * sizeof(int));
free(ptr);

or

int * ptr = (int *) calloc(10, sizeof(int));
free(ptr);

realloc

int * ptr = (int *) malloc(10 * sizeof(int));
ptr = realloc(ptr, 20*sizeof(int));