How do C libraries store state variables?

Iโ€™ve been developing in C for a while, coming from object-oriented languages โ€‹โ€‹like C ++ and Java, and using standard library functions like fread() and strtok() , I began to wonder how these functions go about storage variables related to their state?

For example, strtok() behaves differently for subsequent calls, and fread() tracks your position in the file. This information should be stored somewhere, and in an object-oriented language, there are area constructs such as private or protected to protect these values โ€‹โ€‹from undesirable modification, but as I understand it, C does not have these.

So how are they stored safely? Or are they really global and can be changed anywhere? The question arose when I wrote a header file with utility functions that were supposed to store similar status information. What is the โ€œrightโ€ way to do things like this in C, and how are they handled in existing libraries?

+5
source share
2 answers

These calls use static variables. A local static variable retains its value between function calls. A global static variable or function is accessible only by other functions declared in the same file.

+7
source

In the case of fread (), the state is stored in the FILE structure. A structure is a resource allocated by fopen() that returns a pointer to it, and you pass that pointer to each call to the file operation. The resource is freed when fclose() called. The FILE resource can be allocated from the static pool or can be dynamically allocated from the heap - this depends on the implementation. For instance:

 RESOURCE* getResource() { return malloc( sizeof(RESOURCE) ) ; } int useResource( RESOURCE* r ) { return r.index++ ; } void releaseResource( RESOURCE* r ) { free( r ) ; } 

strtok() , on the other hand, contains an internal static pointer, which is initialized when passing a string and is used as a starting point for passing a null pointer.

For instance:

 int getState() { static int state = 0 ; return state++ ; } int main() { int s ; do { s = getState() ; printf( "state = %d\n", s ; } while( s < 10 ) ; } 
+8
source

Source: https://habr.com/ru/post/1209486/


All Articles