CS 330 Lecture 12 – Malloc, Classless Data Structures, and Make
February 18, 2013 by Chris Johnson. Filed under cs330, lectures, spring 2013.
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;
show
int a[] = {1, 3};
int *b = a + 1;
*b = 19;
show
int a = 17;
int *b = NULL;
*b = *b;
show
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
show