In C, how to issue a global static pointer?

In C, please review these codes,

static char* test = NULL;
typedef struct
{
    char* member1;
}TestStruct;


void testCode()
{
    TestStruct ts;
    test = malloc(10*sizeof(char));
    //assign characters to each test 0 ~ 9 positions 
    ts.member1 = test;
    // using ts, then can I free static pointer test using free()?
    free(test);
}

1) Is this free code correct?
2) The allocated memory check task is on the heap, right?
3) is the test located in .bss?
4) if the testCode () function can be called in the stream, the test is one, right? but every time the thread calls testCode (), the test will be assigned a new pointer and there will be a memory leak, right? So, can I use this code to avoid it?

 Mutex_Start
 if(test == NULL)
     test = malloc(10*sizeof(char));
 Mutex_End

Please help me.

+4
source share
4 answers

Is this the correct free code?

, 10 , , , , .

, . ts.member1 = test; . . , free(test), test ts.member1 .

, ?

.

test .bss?

.

testCode() , , ?

, , . free() . , , free(), . :

  • 1: malloc 1234
  • 1234
  • 2: malloc 5678
  • 5678
  • 1234 -
  • 2: 5678. : free() NULL.
  • 2:
  • 1: 5678 ( - )
  • 1:

, .

, , ?

NULL . , , . , . , , , .

+5

,

test = NULL; 

free(test);

​​ , mallocing

+3

free , atexit, . , .

. C, AKA C11 , , , , .

static char*_Atomic test = ATOMIC_VAR_INIT(0);


void testCode(void)
{
    TestStruct ts;
    while (!test) {
      char* tmp = malloc(10*sizeof(char));
      if (!atomic_compare_exchange(&test, tmp, 0))
        free(tmp);
    }
   /* Do whatever you have to do, here */
   ...
}

C11, P99.

+1

, , , , malloc , . :

static char* test = NULL;
static int refCount = 0;

void testCode()
{
    TestStruct ts;

    {
        //mutex lock;
        if (!refCount++)
            test = malloc(10*sizeof(char));
    }

    //assign characters to each test 0 ~ 9 positions 
    ts.member1 = test;

    {
        //mutex lock;
        if (!--refCount)
            free(test);
    }
}

If the global pointer is some kind of global resource, and the threads should not work on it in parallel, you should put the mutex around the entire function from malloc to free. If you are only protecting malloc and freeing yourself separately, one thread can free up memory in which another thread is running!

0
source

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


All Articles