C problem. If do malloc() and free() repeatedly, what will happen to the system? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

C problem. If do malloc() and free() repeatedly, what will happen to the system?

If there is a pointer, I malloc() then free() repeatedly, will any problem happen to the system?

16th Jan 2022, 5:46 PM
Joyce Tsai
Joyce Tsai - avatar
4 Answers
+ 1
Joyce Tsai in my previous answer I thought you meant repeating both malloc and free together in proper sequence. Now I understand you are asking about freeing the same pointer more than once after a single malloc. If your code is doing that, then here is a big RED ALERT. If you free the same pointer repeatedly, the behavior is undefined. It may cause an exception. It may be ignored. Or it may have some truly serious consequences that literally could make the difference between life or death of a person. That might sound extreme to you, but I am serious and speaking from personal experience. I was hired once to track down an irreproducible bug in a medical imaging system that on rare occasions returned wrong images. After 1.5 years of searching and testing millions of lines of code, the problem turned out to be that the code was freeing unallocated pointers. Please take this warning seriously and always set your pointers to NULL immediately after freeing them.
17th Jan 2022, 12:42 PM
Brian
Brian - avatar
+ 3
It might cause problems with buggy immature operating systems, but no, there is no theoretical reason that it should cause hiccups or convulsions. That being said, you can probably craft an extreme sequence of mallocs and frees that cause memory fragmentation and failures to find enough contiguous memory to allocate.
16th Jan 2022, 9:15 PM
Brian
Brian - avatar
+ 1
Thank you. This is really helpful to me!!!
18th Jan 2022, 5:39 PM
Joyce Tsai
Joyce Tsai - avatar
0
I also think may cause memory framentation, but already free(), does it still cause this problem ?
17th Jan 2022, 8:48 AM
Joyce Tsai
Joyce Tsai - avatar