Address arithmetic

Added example for address arithmetic demo using alloc
This commit is contained in:
kdeng00
2021-11-15 21:15:20 -05:00
parent 587504818d
commit cdbd6d2ad1
3 changed files with 100 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
#include "alloc.h"
#include <stdio.h>
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;
}
}
+10
View File
@@ -0,0 +1,10 @@
#define ALLOCSIZE 9500
static char allocbuf[ALLOCSIZE];
static char *allocp = allocbuf;
char *alloc(int n);
void afree(char *p);
+69
View File
@@ -0,0 +1,69 @@
/*
*
* Rudimentary memory allocation demo
*
* Author: Kun Deng
*/
#include <stdio.h>
#include <string.h>
#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;
}