diff --git a/ch_05/alloc_demo/alloc.c b/ch_05/alloc_demo/alloc.c new file mode 100644 index 0000000..27a031a --- /dev/null +++ b/ch_05/alloc_demo/alloc.c @@ -0,0 +1,21 @@ +#include "alloc.h" + +#include + + +char *alloc(int n) +{ + if (allocbuf + ALLOCSIZE - allocp >= n) { + allocp += n; + return allocp - n; /* old pointer */ + } else { + return 0; + } +} + +void afree(char *p) +{ + if (p >= allocbuf && p < allocbuf + ALLOCSIZE) { + allocp = p; + } +} diff --git a/ch_05/alloc_demo/alloc.h b/ch_05/alloc_demo/alloc.h new file mode 100644 index 0000000..9b3ac28 --- /dev/null +++ b/ch_05/alloc_demo/alloc.h @@ -0,0 +1,10 @@ + +#define ALLOCSIZE 9500 + +static char allocbuf[ALLOCSIZE]; +static char *allocp = allocbuf; + + +char *alloc(int n); + +void afree(char *p); diff --git a/ch_05/alloc_demo/main.c b/ch_05/alloc_demo/main.c new file mode 100644 index 0000000..76b61ac --- /dev/null +++ b/ch_05/alloc_demo/main.c @@ -0,0 +1,69 @@ +/* + * + * Rudimentary memory allocation demo + * + * Author: Kun Deng + */ + +#include +#include + +#include "alloc.h" + + +void populate_ptr(char *ptr, const int size); +void print_ptr(char *ptr, const int size); + + +void populate_ptr(char *ptr, const int size) +{ + for (int i = 0; i < size; ++i) { + switch (i) { + case 0: + *(ptr+i) = '1'; + break; + case 1: + *(ptr+i) = '9'; + break; + case 2: + *(ptr+i) = '7'; + break; + case 3: + *(ptr+i) = '2'; + break; + default: + *(ptr+i) = ' '; + break; + } + } +} + +void print_ptr(char *ptr, const int size) +{ + for (int i = 0; i < size; ++i) { + printf("index: %d ptr value: %c\n", i, *(ptr+i)); + } + + if (strcmp(ptr, "1972") == 0) { + printf("Thick as a Brick and Close to the Edge... Yes, %s was a good year for music\n", ptr); + } else { + printf("Full value: %s\n", ptr); + } +} + + +int main() +{ + printf("alloc demo\n"); + + const int ptr_size = 4; + char *sequence = alloc(ptr_size); + + populate_ptr(sequence, ptr_size); + print_ptr(sequence, ptr_size); + + afree(sequence); + + + return 0; +}