The memory management of struct in C should be careful, especially when there are pointers inside struct. If there is a pointer inside struct, the pointer content will not be released, this is quite troublesome when calling the struct interface written by others. This requires the other party to provide the struct interface and additional memory management support. Otherwise, problems may occur easily, at this point, the constructor and destructor of C ++ are much better. Below is an example of free struct C:
# Include
# Include
Struct Test
{
Char * p_ch;
Int IX;
};
Int main (INT argc, char * argv [])
{
Struct test * p_test;
P_test = malloc (sizeof (struct test ));
P_test-> p_ch = malloc (20 );
Char * p_ch = "Hello! ";
Strcpy (p_test-> p_ch, p_ch );
P_ch = p_test-> p_ch;
Printf ("p_test-> p_ch:/T % s/n", p_test-> p_ch );
Free (p_test-> p_ch); // if this line is commented out, the p_ch value is still "Hello !"
Free (p_test );
Printf ("after free (p_test), p_ch:/T % s/n", p_ch );
System ("pause ");?
Return 0;
}