John Vulconshinz
John Vulconshinz

Reputation: 1148

Static Variables - C

I am writing a program that shares a globaly declared pointer to a buffer that could be used by all the functions within the program. But the buffer is not necessary in certain cases so the pointer is left NULL until it is initaly allocated by evualting it's NULL status. I also need a globaly declared integer to prevent against buffer overflows and to reallocate if necessary. Just because I am writing this program for practice I want the buffer size integer to be declared staticly when the buffer is allocated. For example this code segment would allocate the inital memory size for the buffer.

static char *buffer //(Globaly Declared) I know that the static part is implied I just want to put emphasis on it.

while(program has arguments to do)//Not actual code. I put this here to give an idea of where the statement is located
{
   //None relavant code here..


    if(buffer is necessary)//Not actual code. I put this here to give an idea of where the statement is located
    {
          if(buffer == NULL)
          {
             static unsigned int initial_value = 64;
             static unsigned int *buffer_size = &inital_value;

              if( (buffer = malloc(sizeof(char)*inital_value+1)) == NULL)
              {
                 perror("MALLOC ERROR");
                 return 1;
               }
           }
      }
 }

I have a few questions about how this works(if it does) and how static memory in general works.

Upvotes: 0

Views: 206

Answers (2)

0x90
0x90

Reputation: 41012

static unsigned int initial_value = 64;
static unsigned int *buffer_size = &inital_value;

Both will be initialized only once on the first execution and they are located on the global memory, within the scope derived by {}.

Upvotes: 1

Michael Greene
Michael Greene

Reputation: 10423

The pointer is statically allocated, but the memory it points to is dynamically allocated, only when your if conditional holds true.

Deallocation of the "variable" (the pointer) is handled for you, but deallocation of the memory it points to is not handled for you. You will need to free anything you malloc.

You're right that you could write (initial_value+1) or initial_value + 1. The terminating NULL byte does need to be the same size (byte / char) as the rest of the array. In C, all array elements are the same size. You may find (initial_value+1) better reflects that.

Upvotes: 2

Related Questions