Advertisement

Allocating memory problem

Started by February 14, 2002 03:27 PM
2 comments, last by Owie 22 years, 10 months ago
Sorry to bother you all with debug questions, but if I get an "Unhandled exception in Program.exe: 0xC0000005: Access Violation" when I call CurrentField->NextField = new _Field; is it leaking out somewhere bad or what??
its not leaking, CurrentField must be NULL (not initialized), so when you try to access NextField, the program tryes to access the memory at NULL (0) which is not a valid page for your program, hence the access violation, try

CurrentField = new _Field;
CurrentField->NextField = new _Field;

now, because of the Name CurrentField this seems to be some sort of iterator pointer to a linked list, in case your code is alright, what you should do is check for NULL, if you find null you are beyound your list tail

if(CurrentField!=NULL)
{
CurrentField->NextField = new _Field;
}

Advertisement
This doesnt solve the problem. I debug, and ''CurrentField'' does have a address associated with it. The program actually goes through that loop 4 times before it gets this error. What other things can go wrong when allocating memory. Is it possible to allocate to an already allocated space? I wouldnt think so.

Thanx

yes, it is a linked list.
so, you tried the "if()"?
also make sure you initialize your pointers to NULL (I.E. _Field *CurrentField = NULL) dont just assume the compiler will do it for you, that ensures that the memory does not have garbage in it.

you can do

SomeField = new _Field;
SomeField = new _Field;

and the compiler wont make a peep, but at runtime you will create a leak, make sure you delete everything you new after you dont need it anymore, you can check for nulls too if you have doubts about whether you are realocating memory for a pointer:

if(SomeField==NULL) // its ok to allocate
{
SomeField = new _Field;
}
else
{
printf("tryed to realocate memory");
}

this assumes you follow all your deletes by setting the pointers to null

delete SomeField;
Somefield = NULL;

I think the easiest way to find leaks is by overloading the new and delete operators, there is an artice at flipcode about it

This topic is closed to new replies.

Advertisement