prev up next   top/contents search

comp.lang.c FAQ list · Question 7.19

Q: My program is crashing, apparently somewhere down inside malloc, but I can't see anything wrong with it. Is there a bug in malloc?


A: It is unfortunately very easy to corrupt malloc's internal data structures, and the resulting problems can be stubborn. The most common source of problems is writing more to a malloc'ed region than it was allocated to hold; a particularly common bug is to malloc(strlen(s)) instead of strlen(s) + 1. [footnote] Other problems may involve using pointers to memory that has been freed, freeing pointers twice, freeing pointers not obtained from malloc, freeing null pointers, allocating 0-sized objects (see question 11.26), or trying to realloc a null pointer (see question 7.30). (The last three--freeing null pointers, allocating 0-sized objects, and reallocing a null pointer--are sanctioned by the Standard, though older implementations often have problems.) Consequences of any of these errors can show up long after the actual mistake and in unrelated sections of code, making diagnosis of the problem quite difficult.

Most implementations of malloc are particularly vulnerable to these problems because they store crucial pieces of internal information directly adjacent to the blocks of memory they return, making them easy prey for stray user pointers.

See also questions 7.15, 7.26, 16.8, and 18.2.


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North