EmiX
EmiX

Reputation: 51

Deleting Global allocated memory in C++

Today i tried to create global pointer:

int *map = new int[M2*N2];

then i tried to delete this in main() function:

delete[] map;
map = NULL;

But after executing all program it gives error:

free(): invalid next size (fast)

So, Is it possible to create such pointer and then delete it anywhere else?

Edit

Its Fixed.

M2 was M+1 (M was limit for array), After using M2=M+10 it worked.

Thanks to all...

Upvotes: 0

Views: 1283

Answers (1)

Mike DeSimone
Mike DeSimone

Reputation: 42805

The error seems to be saying that, when it is trying to clean up your memory block, the size stored for the next heap block is invalid. This information is normally stored in small header blocks, just before the pointer you get from new.

...--+----------------+--------+----------+------------+------------+--...
     | previous block | block  | block    | next block | next block |
     | data           | header | data     | header     | data       |
...--+----------------+--------+----------+------------+------------+--...
                                ^          ^
                                |          |
new[] returns pointer here -----+          |
You probably wrote into here --------------+
meaning the OS can no longer find blocks after there.

I would bet that you are writing to memory outside the bounds of the array. In other words, you're accessing an index less than 0 or greater than or equal to M2*N2. (Since it's complaining about the next heap block header being corrupt, it's probably the latter case.)

Turn off parts of your code until free() stops complaining. Then turn on parts you turned off until it starts again. Narrow it down to a few, or one, lines that causes the problem, then fix it.

EDIT: Now that you've determined that a larger array works around the problem--it does not fix it--you should initialize the "out of bounds" parts of your array to some known constant (pick a number, preferably one unlikely to be in your data) and then at the end of your program, you can see what out-of-bounds elements were changed.

In the end, if your code does not work with int *map = new int[M*N];, then it is faulty code. If one of my subordinates told me M2=M+10 was a final fix for the code, I'd fire them. That's nothing more than a latent bug waiting to come back and bite you, probably right when a deadline hits.

Upvotes: 7

Related Questions