+ 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?
4 odpowiedzi
+ 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.
+ 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.
+ 1
Thank you. This is really helpful to me!!!
0
I also think may cause memory framentation, but already free(), does it still cause this problem ?