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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With