/share/doc/papers/malloc/problems.ms

https://bitbucket.org/freebsd/freebsd-head/ · Unknown · 54 lines · 54 code · 0 blank · 0 comment · 0 complexity · 7ed9ab9cc45a69a554c9ad9bea52f9fd MD5 · raw file

  1. .\"
  2. .\" ----------------------------------------------------------------------------
  3. .\" "THE BEER-WARE LICENSE" (Revision 42):
  4. .\" <phk@FreeBSD.org> wrote this file. As long as you retain this notice you
  5. .\" can do whatever you want with this stuff. If we meet some day, and you think
  6. .\" this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
  7. .\" ----------------------------------------------------------------------------
  8. .\"
  9. .\" $FreeBSD$
  10. .\"
  11. .ds RH The problems
  12. .NH
  13. The problems
  14. .PP
  15. Even though malloc(3) is a lot simpler to use
  16. than the raw brk(2)/sbrk(2) interface,
  17. or maybe exactly because
  18. of that,
  19. a lot of problems arise from its use.
  20. .IP
  21. Writing to memory outside the allocated chunk.
  22. The most likely result being that the data structure used to hold
  23. the links and flags about this chunk or the next one gets thrashed.
  24. .IP
  25. Freeing a pointer to memory not allocated by malloc.
  26. This is often a pointer that points to an object on the stack or in the
  27. data-section, in newer implementations of C it may even be in the text-
  28. section where it is likely to be readonly.
  29. Some malloc implementations detect this, some don't.
  30. .IP
  31. Freeing a modified pointer. This is a very common mistake, freeing
  32. not the pointer malloc(3) returned, but rather some offset from it.
  33. Some mallocs will handle this correctly if the offset is positive.
  34. .IP
  35. Freeing the same pointer more than once.
  36. .IP
  37. Accessing memory in a chunk after it has been free(3)'ed.
  38. .PP
  39. The handling of these problems have traditionally been weak.
  40. A core-dump was the most common form for "handling", but in rare
  41. cases one could experience the famous "malloc: corrupt arena."
  42. message before the core-dump.
  43. Even worse though, very often the program will just continue,
  44. possibly giving wrong results.
  45. .PP
  46. An entirely different form of problem is that
  47. the memory returned by malloc(3) can contain any value.
  48. Unfortunately most kernels, correctly, zero out the storage they
  49. provide with brk(2), and thus the storage malloc returns will be zeroed
  50. in many cases as well, so programmers are not particular apt to notice
  51. that their code depends on malloc'ed storage being zeroed.
  52. .PP
  53. With problems this big and error handling this weak, it is not
  54. surprising that problems are hard and time consuming to find and fix.