LoveTW
LoveTW

Reputation: 3842

debug error when doing memory release

The purpose of below code is to correct the false value(-1) to right value, but when i use a dynamic array to record the correct value, the debug error happen. Can someone help me? Thanks.

code.cpp

int size = DFS_CODE.size();
int *code = new int[DFS_CODE.size()];

for(int i = 0; i < DFS_CODE.size(); i++) {
    if(DFS_CODE[i].fromlabel == -1)
        DFS_CODE[i].fromlabel = code[DFS_CODE[i].from];
    else if(DFS_CODE[i].tolabel == -1)
        DFS_CODE[i].tolabel = code[DFS_CODE[i].to];

    code[DFS_CODE[i].from] = DFS_CODE[i].fromlabel;
    code[DFS_CODE[i].to] = DFS_CODE[i].tolabel;

    cout << DFS_CODE[i].from << "(" << DFS_CODE[i].fromlabel << ") => "
         << DFS_CODE[i].to << "(" << DFS_CODE[i].tolabel << ")" << endl;
}
delete [] code;

debug error

debug error!
HEAP CORRUPTION DETECTED:after Normal block(#1363) at 0x005745F0. 
CRT detected that the application wrote to memory after end of heap buffer.

I found the debug error will also happen when i use malloc. When I take delete [] code; or free(code);, the debug error will happen. Why? shouldn't i release the memory?

I solve this problem by another way, i use map struct to store the right value. Thanks for everyone who help me! Best regards!

map <int, int> code;

for(int i = 0; i < DFS_CODE.size(); i++) {
    if(DFS_CODE[i].fromlabel != -1)
        code[DFS_CODE[i].from] = DFS_CODE[i].fromlabel;
    if(DFS_CODE[i].tolabel != -1)
        code[DFS_CODE[i].to] = DFS_CODE[i].tolabel;

    cout << DFS_CODE[i].from << "(" << code[DFS_CODE[i].from] << ") => "
         << DFS_CODE[i].to << "(" << code[DFS_CODE[i].to] << ")" << endl;
}

Upvotes: 0

Views: 154

Answers (2)

guga
guga

Reputation: 724

Note that when you allocate your memory for 'code' it is not initialized

int *code = new int[DFS_CODE.size()];

And the code below uses it...

for(int i = 0; i < DFS_CODE.size(); i++) {
    if(DFS_CODE[i].fromlabel == -1)
        DFS_CODE[i].fromlabel = code[DFS_CODE[i].from];
    else if(DFS_CODE[i].tolabel == -1)
        DFS_CODE[i].tolabel = code[DFS_CODE[i].to];

This may be causing DFS_CODE to receive undefined values, what is not your problem, but is suspicious...

Upvotes: 0

Doug T.
Doug T.

Reputation: 65629

Suspicious to me are these lines

code[DFS_CODE[i].from] = DFS_CODE[i].fromlabel;
code[DFS_CODE[i].to] = DFS_CODE[i].tolabel;

As you allocate code as follows

int *code = new int[DFS_CODE.size()];

Make sure you check that .from and .to are < DFS_CODE.size() and >= 0, otherwise you're writing outside of your heap allocated array which can cause heap corruption.

Also, is there a reason you don't replace the array code entirely with

std::vector<int> code

?

Upvotes: 2

Related Questions