In C, how to release global static pointer?

c, free, pointers, static

Solution

Is this free code right?

If the intent is to allocate 10 bytes of memory, then assign a pointer to point at that memory, then delete the memory, then it is correct.

But the comment in the code suggests that you are a bit confused. `ts.member1 = test;` will only make another pointer point at the same chunk of data. You have not made a hard copy of anything. From the moment when you `free(test)`, then both `test` and `ts.member1` are pointing at invalid memory.

Allocated memory test pointing is in heap, right?

Yes.

test is in .bss?

Yes.

if testCode() function can be called in thread, test is one, right?

Every time the function is called, a new chunk of memory will be created. But the same function also `free()` the memory. Of course, if another thread gets focus before the first one reaches `free()`, it will allocate yet another chunk of memory. Example:

- Thread 1: malloc memory at address 1234

- Test is pointing at 1234

- Context switch

- Thread 2: malloc memory at address 5678

- Test is pointing at 5678

- Nothing is pointing at 1234 any longer - memory leak

- Thread 2: free memory at address 5678. NOTE: free() does not set the pointer to NULL.

- Thread 2: done

- Thread 1: free memory at address 5678 (test is still pointing there)

- Thread 1: crash & burn

So you have a memory leak and a runtime crash both.

So, can I use this code to avoid it?

The check against NULL prevents the second thread from allocating any new memory. If that is the intention and both threads are supposed to access the same memory, then it will prevent against the above mentioned bug. But the actual memory will have to be protected against race conditions as well, the code gets complex. The proper way to do this is likely to allocate everything locally, rather than through a file scope pointer.

Problem

In C, please look over this 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 right? 2) Allocated memory test pointing is in heap, right? 3) test is in .bss? 4) if testCode() function can be called in thread, test is one, right? but every time thread calls testCode(), test will be assigned with new pointer and makes 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.

Original source