CS157

CS157: Intro to C, Part II

Spring 2018

Dynamic Memory

See this page as a slide show

Dynamic Memory Allocation

Dynamic Memory Allocation

malloc(…)

size_t

size_t is a typedef for an unsigned numeric type, often unsigned long int. It’s used as an argument to functions like malloc, when a number of bytes is required.

strlen and sizeof return a size_t.

Print a size_t with %zu, thus:

char god[] = "Thor of Asgard";
printf("%d\n", sizeof(god));        // not quite right
printf("%zd\n", sizeof(god));       // not quite right
printf("%zu\n", sizeof(god));       // correct
c.c: In function 'main':
c.c:2: warning: format '%d' expects argument of type 'int', but argument 2 has type 'long unsigned int'
15
15
15

sizeof(…)

free(…)

A poem about memory deallocation

If you forget to free p,
eventually,
you run out of memory!
Do you C?

calloc(…)

int *p = calloc(10, sizeof(int));
for (int i=0; i<10; i++)
    printf(" %d", p[i]);
 0 0 0 0 0 0 0 0 0 0

realloc(…)

void *realloc(void *p, size_t size)
    int *p = malloc(100*sizeof(int));
    …
    p = realloc(p, 200*sizeof(int));

Example allocations

    int *grades;
    int numgrades = 15;
    grades = malloc(numgrades * sizeof(int));

    int size = 10;
    char *base = calloc(size, sizeof(char));

    free(base);
    free(grades);

Example

Dynamically create an array of grades, asking the user how many, then prompting the user for each grade.

int numgrades;
int *grades;           // ptr to array of grades
printf("How many students? ");
scanf("%d", &numgrades);

// get memory for the entire array
grades = malloc(numgrades * sizeof(int));
if (grades == NULL) {     // snafu?
    printf("Failed to allocate grades array\n");
    return 1;
}
for (int i=0; i<numgrades; i++) {
    printf("Enter a grade: ");
    scanf("%d", &grades[i]);
}
for (int i=0; i<numgrades; i++)
    printf("Value %d: %d\n", i, grades[i]);
free(grades);

How Can This Work?

Example

% c11 -o dym2 dynMem2.c
% ./dym2
Array size: 4
a, b, c, d

Dynamically create a repeating array of the alphabet.

    int size;
    printf("Array size: ");
    scanf("%d", &size);
    char *base = calloc(size, sizeof(char)); // calloc: handy for arrays
    /* Should check for failure here */
    for (int i=0;i<size;i++)
        base[i] = 'a' + i%26;
    for (int i=0;i<size;i++) {
        if (i != 0)
            printf(", ");
        printf("%c", base[i]);
    }
    printf("\n");
    free(base);

Leaking

The dreaded Memory Leak

Memory

Memory is divided into two parts: the stack & the heap.

A stack is a common structure used in computers and in programming. The basics are the same, but here we are talking about memory management as opposed to programming it in our code.

Until now, we’ve mostly used the stack:

  • Local Variables
  • Parameters

The Stack

The Heap

Memory Leaks

free

A Few Details

Finding Problems

Example

char str[8] = "spam\n"
char *ptr;


        ┌───┐         ┌────┬────┬────┬────┬────┬────┬────┬────┐
    ptr:│ ? │     str:│ s  │ p  │ a  │ m  │ \n │ \0 │ ?? │ ?? │
        └───┘         └────┴────┴────┴────┴────┴────┴────┴────┘

Example

char str[8] = "spam\n";
char *ptr;
ptr = malloc(sizeof(char)*(strlen(str)+1));


        ┌───┐         ┌────┬────┬────┬────┬────┬────┬────┬────┐
    ptr:│   │     str:│ s  │ p  │ a  │ m  │ \n │ \0 │ ?? │ ?? │
        └─┼─┘         └────┴────┴────┴────┴────┴────┴────┴────┘
          │
          ∨  
        ┌────┬────┬────┬────┬────┬────┐
        │ ?? │ ?? │ ?? │ ?? │ ?? │ ?? │
        └────┴────┴────┴────┴────┴────┘

Example

char str[8] = "spam\n";
char *ptr;
ptr = malloc(sizeof(char)*(strlen(str)+1));
strcpy(ptr, str);

        ┌───┐         ┌────┬────┬────┬────┬────┬────┬────┬────┐
    ptr:│   │     str:│ s  │ p  │ a  │ m  │ \n │ \0 │ ?? │ ?? │
        └─┼─┘         └────┴────┴────┴────┴────┴────┴────┴────┘
          │
          ∨  
        ┌────┬────┬────┬────┬────┬────┐
        │ s  │ p  │ a  │ m  │ \n │ \0 │
        └────┴────┴────┴────┴────┴────┘

Example

char str[8] = "spam\n";
char *ptr;
ptr = malloc(sizeof(char)*(strlen(str)+1));
strcpy(ptr, str);
free(ptr);             // Assume that we’re done with it

        ┌───┐         ┌────┬────┬────┬────┬────┬────┬────┬────┐
    ptr:│   │     str:│ s  │ p  │ a  │ m  │ \n │ \0 │ ?? │ ?? │
        └─┼─┘         └────┴────┴────┴────┴────┴────┴────┴────┘
          │
          ∨  
        ┌────┬────┬────┬────┬────┬────┐
        │ ?? │ ?? │ ?? │ ?? │ ?? │ ?? │
        └────┴────┴────┴────┴────┴────┘

strdup

char foo[] = "Hello";
char *bar = strdup(foo);
bar[0] = 'J';
printf("%s %s\n", foo, bar);         // Displays Hello Jello

While we are talking about memory …

dst: destination
src: source
len: length

memcpy(dst, src, len)

memmove(dst, src, len)

memset(dst,val,len)

Modified: 2017-12-19T11:20

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building