How to solve munmap_chunk(): invalid pointer error in C++

后端 未结 2 423
终归单人心
终归单人心 2020-12-13 17:24

I have an application in C++ and OpenCV which tries to use the classification model realized with SVMLight in order to add the weight values which can be use for HOG Calssif

相关标签:
2条回答
  • 2020-12-13 17:46

    This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

    The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

    char *words; // setting this to NULL would have prevented the issue
    
    if (condition) {
        words = malloc( 512 );
    
        /* calling free sometime later works here */
    
        free(words)
    } else {
    
        /* do not allocate words in this branch */
    }
    
    /* free(words);  -- error here --
    *** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/
    

    There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

    *** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
    *** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
    glibc detected, realloc(): invalid pointer


    IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

    0 讨论(0)
  • 2020-12-13 18:13

    The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

    0 讨论(0)
提交回复
热议问题