views:

198

answers:

4

Hi Guys, I have a high memory requirement in my code and this statement is repeated a lot of times:

Node** x;
x = new Node*[11];

It fails at this allocation. I figured out this line by throwing output to the console!

I am building my code on Visual Studio. It works fine in Debug mode (both in VS2005 and VS2008) However it throws the error in VS2005 Release mode. A direct exe generated from cl Program.cpp works if cl is from VS2010 but fails when it's from VS2005. Any clues?

PS: Linux gives me a Bus Error(core dumped) for the same Thanks

UPDATE: And I guess, it can be due to 'unaligned' thing as I understand. I just made 11 to 12 (or any even number) and It works!!! I don't know why. It doesn't work with odd numbers!

Update 2 : http://www.devx.com/tips/Tip/13265 ?

+3  A: 

I think you've done something somewhere else which corrupted the program heap: for example, writing past the end of an allocated chunk of memory, or writing to a chunk of memory after it's been freed.

I recommend that the easiest way to diagnose the problem would be to run the software using a kind of debugger that's intended to detect this kind of problem, for example valgrind.

ChrisW
+2  A: 

I have a high memory requirement in my code

Are you actually running out of memory?

x = new Node*[11];

Are you deleting x like so:

delete [] x;   // the correct way

or:

delete x;  // incorrect

Or there could simply be something else corrupting the heap, though I would have expected that running in debug mode mode would make it more obvious, not less so. But with heap corruption there are rarely any guarantees that it'll do so in a nice, easy to debug way.

Michael Burr
Thanks for pointing delete []x thing.But the error happens at the allocation point - I think I am very sure of that. Please see my comment above!Thanks.
Trilok
If you use the wrong delete, the problem might not occur at the delete, but later when another allocation occurs if the prior incorrect delete has corrupted the heap data structures.
Michael Burr
+2  A: 

There is nothing wrong with this code.

Node **x;
x = new Node*[11];

You are allocating 11 pointers to class Node and storing it as a double-pointer in variable x. This is fine.

The fact that your program is crashing here is probably due to some memory error that is occurring elsewhere in your program. Perhaps you're writing past array bounds somewhere. If you load this array using a for loop, double-check your indexing.

If you have access to a memory profiler, I'd recommend using it. These bugs can be difficult to track down in large programs.

Matt Davis
+2  A: 

A valid C++98 implementation will throw an exception (std::bad_alloc) if allocation fails, not just crash. I'd agree with previous answers and suggest running your program in valgrind as this reeks of memory corruption. Valgrind should be available in your Linux distribution of choice.

Stephen Newell