开发者

Memory Error in C++

I have a high memory requirement in my code and this statement is repeated a lot of tim开发者_开发问答es:

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 ?


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.


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜