When to declare a local variable as static in C?

I recently learned about storage classes in C. In particular, I was fascinated by the storage class static. Based on Haskell, I avoid the concept of passing an output buffer to a function to get the result. For example, consider the following function readfile:

#include <stdio.h>

void readfile(const char * filename, char * contents, size_t size) {
    FILE * file = fopen(filename, "rb");
    fread(contents, size, 1, file);
    contents[size] = 0;
    fclose(file);
}

There are several reasons why I don’t like this code:

  • Using voidas return type annoys me. I do not know why. He just does.
  • Passing the output buffer to a function seems unnatural. Mutable state is error prone.
  • You do not need to pass the number of bytes to read as an input parameter to the function.
  • You need to create a buffer manually and predict the file size.

- :

#include <stdio.h>
#include <malloc.h>

char * readfile(const char * filename) {
    FILE * file = fopen(filename, "rb");

    fseek(file, 0, SEEK_END);
    size_t size = ftell(file);
    fseek(file, 0, SEEK_SET);

    static char * contents;
    contents = malloc(size + 1);
    fread(contents, size, 1, file);
    fclose(file);

    contents[size] = 0;
    return contents;
}

, , , - readfile. . , , free , .

, contents static , , , . -, , .

, static : , , , , . static, ?

, ? , C (, ..).

+3
3

static C.

static , . , , , : readfile , malloc contents, malloc contents, fread contents , , , , .

static , contents . , , : , , , . static , , , , , . , .

, static, , , . :

static const int some_integers[] = { 1, 2, 3, 4 };

.

, static . , , , , , .

+5

POSIX, stat(2) fstat(2), . , .

, , mmap(2) CreateFileMapping MapViewOfFile, .

0

Using static in this case will effectively make variable memory memory stored in the global process memory data segment. However, it will only have local coverage (only this function sees it). Since you are most likely going to track the pointer in some other way (return value), there is no need to use this method and spend the pointer on the value of the global data memory (maybe not important).

0
source

All Articles