Search code examples
c++runtime-errorfreeallocation

Error in `/tmp/Main': free(): invalid next size (fast): No dynamic allocation


So, I'm doing a problem called "Unique Paths II" in lintcode. However, I encountered a runtime error during a testcase:

// in the context, map is the 2d array that saves the obstacle path as described in the question, which fits common code practices
    for (int i = 1; i < n; i++) {
        if (map[0][i] != 1)
        map[0][i] = 1;
        else{
            for(;i<m;i++){
                map[0][i] = 0;
            }
            break;
        }
    }

Lintcode gives me this error:

*** Error in `/tmp/Main': free(): invalid next size (fast): 0x0000000001bb5130 *** ======= Backtrace: ========= [0x625861] [0x62dda6] [0x631dd7] [0x40f00a] [0x40c78e] [0x409cda] [0x407823] [0x4062a7] [0x410cd9] [0x40e361] [0x40bbb0] [0x40912d] [0x406ca1] [0x405b96] [0x4031ce] [0x6038c6] [0x603aba] [0x400d69] ======= Memory map: ======== 00400000-007d9000 r-xp 00000000 ca:01 890688 /tmp/Main 009d8000-009e4000 rw-p 003d8000 ca:01 890688 /tmp/Main 009e4000-009e9000 rw-p 00000000 00:00 0 01b92000-01bd6000 rw-p 00000000 00:00 0 [heap] 7f5660000000-7f5660047000 rw-p 00000000 00:00 0 7f5660047000-7f5664000000 ---p 00000000 00:00 0 7f5666690000-7f5666691000 rw-p 00000000 00:00 0 7ffea1f83000-7ffea1fa4000 rw-p 00000000 00:00 0 [stack] 7ffea1ff0000-7ffea1ff3000 r--p 00000000 00:00 0 [vvar] 7ffea1ff3000-7ffea1ff5000 r-xp 00000000 00:00 0 [vdso] ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall] Aborted (core dumped)

What is wrong here?


Solution

  • Regardless of the error you should read Why is “using namespace std;” considered bad practice? and enable compiler warnings. In your code are many

    warning: implicit conversion changes signedness: 'int' to 'size_type' (aka 'unsigned long') [-Wsign-conversion]
    

    and

    warning: implicit conversion loses integer precision: 'size_type' (aka 'unsigned long') to 'int' [-Wshorten-64-to-32]
    

    You could easily fix it with

    auto m = map.size(), n = map[0].size();
    

    and

    for (decltype(n) i = 1; i < n; i++) {
    

    You can use lldb to debug code compiled with clang.

    The actual error is in the section

    for (int i = 1; i < n; i++) {
        if (map[0][i] != 1)
        map[0][i] = 1;
        else{
            for(;i<m;i++){
                map[0][i] = 0;
            }
            break;
        }
    }
    

    In the outer loop i iterates from 0 to n but in the inner loop i iterates from 0 to m and

    map[0][i]
    

    goes out of bounds.