A new understanding of the use of malloc and the use of malloc
After applying for memory using malloc in the sub-function yesterday, an exception error was unexpectedly found during free. After checking, it was found that the pointer length in actual use had exceeded the applied range.
Here are some notes for using malloc:
1. Do not use it for Free. Otherwise, there will be no problem when free is used for the first time. The second time it will be free a wild pointer, and the program will not know what you are doing free. 2. Do not allocate and release data across processes;
Do not free multiple or zero times;
Check whether the allocation is successful. 3. Pay attention to malloc () and free (). In addition, to ensure that only one valid pointer is free, therefore, the pointer should be set to null after malloc returns fail and free pointers, and the pointer should be determined to be null before free! It should be okay to write code in this way! When the pointer is set to null, it's okay if you love free. 4. malloc a pointer in a function, and the returned value is the pointer, which also needs to be free. 5. Point to the heap memory pointer applied by malloc. Do not pay another value during usage; otherwise, memory leakage will also occur. For example, I am * p = (char *) malloc (sizeof (char) * 100); then I am going to p ++ and then free (p); this will cause problems. The free () parameter must be the header pointer of the memory segment. If you don't give the program anything, it must be in conflict with you. 6. After malloc, the pointer length exceeds the range you applied for in actual use. When you go to free again, there will definitely be a problem! You have applied for ten oceans. You cannot buy ten oceans. In fact, these two functions are not very difficult to use, that is, after malloc () is used up, I think it is enough to give it free (). For example:
1 // Code...
2 char *Ptr = NULL;
3 Ptr = (char *)malloc(100 * sizeof(char));
4
5 if (NULL == Ptr)
6 {
7 exit (1);
8 }
9
10 gets(Ptr);
11
12 // code...
13
14
15 free(Ptr);
16
17 Ptr = NULL;
18
19 // code...
Finally, I posted a message to zhihu yesterday to answer the same question:
Https://www.zhihu.com/question/38970898/answer/125534251