CS 330 Lecture 12 – Malloc, Classless Data Structures, and Make
Agenda
- what ?s
- what does this do?
- two primary reasons for heap storage:
- functions can return data cheaply
- memory needs not always known at compile time
- an EZMALLOC macro
- aplay -c 2 -f S16_LE -r 22050 file
- pointer arithmetic
- fopen, fwrite, fclose
- a stack API
- the need for separate compilation and header files
- makefiles
What Does This Do?
int a = 7; int *b = &a; b = 3;
int a[] = {1, 3}; int *b = a + 1; *b = 19;
int a = 17; int *b = NULL; *b = *b;
TODO
- Breathe.
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
Similar in function, but…
One uses the stack