MC logo

Dynamic Allocation in C (Answer)

  Practice Questions

  1. Calloc is usually used for dynamic arrays, that is, arrays whose size is not known at compile time. Malloc can also be used for dynamic arrays.

  2. To allocate a linked list node:

      #include <stdlib.h>

      struct node_struct *newnode;
      newnode = malloc(sizeof (struct newnode));

      #include <stdlib.h>;

      struct node_struct *newnode;
      newnode = malloc(sizeof *newnode);
    but definitely not

      #include <stdlib.h>

      struct node_struct *newnode;
      newnode = malloc(sizeof newnode);
    which just allocates enough space for a pointer, not for the struct it points to.

  3. To read in a size, then allocate an array of that size:

      #include <stdio.h>
      #include <stdlib.h>

      int m;
      double *darr;

      scanf("%d", m);
      darr = calloc(m, sizeof (double));
    You could also use malloc(m * sizeof (double)) instead of calloc. You must declare darr as a pointer, even though you plan to treat it as an array, because it is dynamically allocated. A declaration in which the size is a variable, as double darr[m], is not correct C, though gcc apparently permits it.

  4. To increase the size of darr by 25 positions: Assuming the value of m has not changed,
    darr = realloc(darr, (m + 25) * sizeof(double));
    Unfortunately, you must know the original size, since realloc requires the new final size, not an increment. There is no way to recover the original allocated size from darr itself.

  5. To copy a string:

      #include <string.h>
      #include <stdlib.h>

      char *copy;
      copy = malloc(strlen(fred) + 1);
      strcpy(copy, fred);
    You cannot just say copy = fred, because that does not create an independent copy. You need +1 to allow for the terminator byte. You must use strlen and not sizeof because it returns the actual length of the string. If fred is a pointer, sizeof fred will give just the size of a pointer, usually too small. If fred is an array, sizeof fred will give the size of the entire array, which may be larger than needed to store the string.

  6. Releasing memory is easy, and there is only one way to do it: free(newnode), free(darr), or free(copy).

<<Pointers and Strings Question ADT Declarations in C>>