ILikeTacos
ILikeTacos

Reputation: 18686

set a breakpoint in malloc_error_break to debug in C++

I'm writing a program that takes 2 command line arguments: a and b respectively.

Everything is good as long as a <= 17.5

As soon as a > 17.5 the program throws the following error:

incorrect checksum for freed object - object was probably modified after being freed

I've narrowed down the problem down to the following piece of code:

for(int a=0; a < viBrickWall.size(); a++) {
    vector<int64_t> viTmp(iK-i);
    fill(viTmp.begin(),viTmp.end(),2);

    for(int b = 0; b < viBrickWall[a].size(); b++) {
         viTmp[viBrickWall[a][b]] = 3;
    }

    viResult.push_back(viTmp);
    viTmp.clear();
}

Removing the latter piece of code, gets rid of the error.

I'm also using valgrind to debug the memory, but I haven't been able to find any solution.

Here it is a copy of valgrind's report:

Report hosted in pastebin

EDIT

I compiled the program with debugging flags:

g++ -g -O0 -fno-inline program.cpp

and ran it with valgrind as follows:

` valgrind --leak-check=full --show-reachable=yes --dsymutil=yes ./a.out 48 10 ``

I noticed the following line:

 ==15318== Invalid write of size 8
 ==15318==    at 0x100001719: iTileBricks(int) (test.cpp:74)
 ==15318==    by 0x100001D7D: main (test.cpp:40)

Line 74 is:

viTmp[viBrickWall[a][b]] = 3;

and Line 40 is:

viBrickWall = iTileBricks(iPanelWidth);

Upvotes: 4

Views: 9759

Answers (1)

scottt
scottt

Reputation: 7238

You're causing an invalid write to heap memory with this line:

viTmp[viBrickWall[a][b]] = 3;

this implies that viBrickWall[a][b] is indexing outside of viTmp at that time. Add

int i = viBrickWall[a][b];
assert(0 <= i && i < viTmp.size());

before the store to viTmp[i] = 3.

HINT: maybe increasing the size of viTmp by one would fix it:

-vector<int64_t> viTmp(iK-i);
+vector<int64_t> viTmp(iK - i + 1);

I don't know the content of viBrickWall so this is just an educated guess from the Valgrind output.

I'm not sure if you're using GNU libstdc++ or libc++ on Mac OSX. If you're using libstdc++ or have a Linux box handy, declare viTmp to be a std::__debug::vector would catch this problem quickly.

Upvotes: 3

Related Questions