-2

I have this implementation of alloc, which allocates memory as a dynamic array.

My question is that what does it mean that the array and pointer are declared static? How does it affect to a function that calls alloc?

#define ALLOCSIZE 10000 /* size of available space */

static char allocbuf[ALLOCSIZE];   /* storage for alloc */
static char *allocp = allocbuf;    /* next free position */

char *alloc(int n)   /* return pointer to n characters */
{

    if (allocbuf + ALLOCSIZE - allocp >= n) {  /* it fits */
        allocp += n;
        return allocp - n; /* old p */
    }  else               /* not enough room */
        return 0;
}
user 004325
  • 49
  • 1
  • 2
  • 7

1 Answers1

1

My question is that what does it mean that the array and pointer are declared static?

It means the lifetime of the arrays is the entire execution of the program. Any object defined at file-scope (with or without the static specifier) has static storage duration (exception: objects defined with C11 _Thread_local specifier). Adding the static specifier limits the visibility of the objects to the source file they are defined.

The total size of your alloc allocations is limited by the size of your allocbuf array.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • So adding the static specifier only limits the visibility of the objects to the source file? – user 004325 Sep 23 '15 at 20:39
  • @user004325 yes, for objects defined at file-scope, adding `static` (versus no storage specifier) makes the objects private to the translation unit. – ouah Sep 23 '15 at 20:40
  • What does this mean in practice? – user 004325 Sep 23 '15 at 20:51
  • @user004325 that you cannot access `allocbuf` array directly from another source file, which is the purpose of adding `static` here. `allocbuf` presence is an implementation detail that is hidden for the `alloc` user. – ouah Sep 23 '15 at 20:57
  • Does alloc do dynamic memory allocation? – user 004325 Sep 24 '15 at 16:58