How can malloc() cause a SIGSEGV?

前端 未结 6 1550
长情又很酷
长情又很酷 2021-01-02 12:09

I have an odd bug in my program, it appears to me that malloc() is causing a SIGSEGV, which as far as my understanding goes does not make any sense. I am using a library cal

6条回答
  •  醉话见心
    2021-01-02 12:32

    There are a myriad ways of triggering a core dump from malloc() (and realloc() and calloc()). These include:

    • Buffer overflow: writing beyond the end of the allocated space (trampling control information that malloc() was keeping there).
    • Buffer underflow: writing before the start of the allocated space (trampling control information that malloc() was keeping there).
    • Freeing memory that was not allocated by malloc(). In a mixed C and C++ program, that would include freeing memory allocated in C++ by new.
    • Freeing a pointer that points part way through a memory block allocated by malloc() - which is a special case of the previous case.
    • Freeing a pointer that was already freed - the notorious 'double free'.

    Using a diagnostic version of malloc() or enabling diagnostics in your system's standard version, may help identify some of these problems. For example, it may be able to detect small underflows and overflows (because it allocates extra space to provide a buffer zone around the space that you requested), and it can probably detect attempts to free memory that was not allocated or that was already freed or pointers part way through the allocated space - because it will store the information separately from the allocated space. The cost is that the debugging version takes more space. A really good allocator will be able to record the stack trace and line numbers to tell you where the allocation occurred in your code, or where the first free occurred.

提交回复
热议问题