Free struct, internal pointer does not free

xiaoxiao2021-03-06  57

C 's memory management needs to be careful, especially in the internal structure of the structure, free falls a pointer to a struct structure. If there is a pointer inside it, the point is not released, this is called when calling someone writing Struct interface It will be quite troubles, which requires the other party to provide additional memory management support in addition to providing the Struct interface, otherwise it is easy to have problems, at this point, the C constructor, the destructor is obviously better, and below is Example of a Free structure of Free Struct:

#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_teest-> p_ch); free (p_test-> p_ch); // If comment This line, 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;}

转载请注明原文地址:https://www.9cbs.com/read-117269.html

New Post(0)