Questions
Does the "memory storage array" allocbuf[10] save everything back to back. For example allocbuf[10] is full with {F, i, r, s, t, \0, S, e, c, \0] and I'll state how allocbuf became full. I imagine all of the information I save into allocbuf saves back to back. So, as an example, after using alloc(6), and assigning the returned character pointer to a variable char *first, the character pointer "first" points to allocbuf[0]. Now I assign, first = "First"; If I want to print "First", do I have to use a for loop,
for (i = 0; i < 6; i++) { print allocbuf[i]; }
to print out "First"?If I assign first = alloc(1) and then assign first = "First", it will work, and overwrite the contents of allocbuf, correct?
Why does the line
printf("allocbuf: %s\n", allocbuf);
not print out the contents of allocbuf in my code?
I'm confident I'll be interested in more features of this program and I am excited to have your help.
I am excited to read any comments about this program, the functions, and memory allocation, although they may not answer on of the specific questions I have. So please share you knowledge and experience with me. Thanks :)
P.S. I haven't encountered malloc() in my book, K&R C Programming 2nd ed, yet, so, please, no comments saying use malloc().
Code
char *alloc(int); //return pointer to free storage in allocbuf[10]
void afree(int *); //free storage in allocbuf[10]
void strcpy2(char *, char *); //copy to, from
static char allocbuf[10];
static char* allocp = allocbuf;
main()
{
char array4[5] = "4444";
char* cp = "overwritten";
char* copy = array4;
char* occupyalloc;
printf("cp: %s\n", cp); //"overwritten"
printf("copy: %s\n", copy); //"4444"
cp = "2"; //overwrite *cp = "overwritten" with *cp = "2"
printf("cp: %s\n", cp); //"2"
occupyalloc = alloc(4); //returns allocp 0, intended storage space is allocbuf[0] through allocbuf[3]
cp = alloc(3); //returns allocp 4, intended use is allocbuf[4] through allocbuf[6]
strcpy2(cp, copy); //copies "4444" into *cp, specifically allocbuf[4] through allocbuf[7]
printf("cp: %s\n", cp); //"4444" , stored in allocbuf[4] through allocbuf[7] improperly
printf("allocbuf: %s\n", allocbuf); //prints allocbuf -- not working
}
char *alloc(int n)
{
if (allocbuf + ALLOCSIZE - allocp >= n)
{
allocp += n;
return allocp - n;
}
else
return 0;
}
void afree(int *initial_storage_element_location)
{
if (initial_storage_element_location >= allocbuf && initial_storage_element_location < allocbuf + ALLOCSIZE)
allocp = initial_storage_element_location;
}
void strcpy2(char *s, char *t)
{
while (*s++ = *t++)
;
}