teaching machines

CS 330 Lecture 12 – Malloc, Classless Data Structures, and Make

February 18, 2013 by . Filed under cs330, lectures, spring 2013.

Agenda

What Does This Do?

  1. int a = 7;
    int *b = &a;
    b = 3;

  2. int a[] = {1, 3};
    int *b = a + 1;
    *b = 19;

  3. int a = 17;
    int *b = NULL;
    *b = *b;

TODO

Code

audioh.c

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

#define EZMALLOC(type, n) \
  (type *) malloc((n) * sizeof(type))

int main(int argc, char **argv) {

  int nsamples = atoi(argv[1]);

  /* short *samples = (short *) malloc(nsamples * sizeof(short) * 2); */
  /* short *samples = (short *) malloc(sizeof(short) * (nsamples +  2)); */

  short *samples = EZMALLOC(short, nsamples * 2);

  int i;
  for (i = 0; i < nsamples * 2; ++i) {
    samples[i] = (short) (rand() / (float) RAND_MAX * 32767);
  }

  FILE *file = fopen("samples.raw", "w");
  fwrite(samples, sizeof(short), nsamples * 2, file);
  fclose(file);

  return 0;
}

Haiku

Malloc versus new
Similar in function, but…
One uses the stack