Member Avatar for tcstom

Hi,
My program keeps coming up with an Access Violation after I moved the code manipulating my linked list from the main function to a sub function. Looking at it with the debugger, I found that the sub function destructs the linked list, and then the main function attempts to distruct it after the sub function has finished running.
What can I do to prevent this from happening?

int WINAPI WinMain(	HINSTANCE hInstance,
					HINSTANCE hPrevInstance,
					LPTSTR    lpCmdLine,
					int       nCmdShow)
{
	CLinkedList<Device>	DeviceList1;
	int numberOfRequestPending1 = DeviceList1.getNumberOfElements();

	Device *newDev1 = new Device();
	newDev1->VendorID=1;
	newDev1->SerialNumber=124;
	DeviceList1.addElement(newDev1);
	Device *newDev2 = new Device();
	newDev2->VendorID=2;
	newDev2->SerialNumber=32414;
	DeviceList1.addElement(newDev2);
	Device *newDev3 = new Device();
	newDev3->VendorID=4;
	newDev3->SerialNumber=36544;
	DeviceList1.addElement(newDev3);
	int numberOfRequestPending2 = DeviceList1.getNumberOfElements();

	AddFromDevicelist(DeviceList1);

	return 0;
}

int AddFromDevicelist(CLinkedList<Device> DeviceList)
{
	DWORD VendorID;
	DWORD SerialNumber;
	CLinkedList<Device>	NewDeviceList;
	int elements = DeviceList.getNumberOfElements();
	while (elements > 0)
	{
		Device *CurrDev = new Device();
		CurrDev=DeviceList.getFirstElement();
		VendorID=CurrDev->VendorID;
		SerialNumber=CurrDev->SerialNumber;
		DeviceList.removeCurrentElement();
		if(AddActiveDevice(VendorID,SerialNumber)==0)
		{
			Device *insDev = new Device();
			insDev->VendorID=VendorID;
			insDev->SerialNumber=SerialNumber;
			NewDeviceList.addElement(insDev);
		}
		elements--;
	}
	elements = NewDeviceList.getNumberOfElements();
	while (elements > 0)
	{
		Device *NewDev = new Device();
		NewDev=NewDeviceList.getFirstElement();
		VendorID=NewDev->VendorID;
		SerialNumber=NewDev->SerialNumber;
		AddNewActiveDevice(VendorID,SerialNumber);
		NewDeviceList.removeCurrentElement();
		elements--;
	}
	return 0;
}

Apologies for the messey code, I just want to solve this problem first before I get in there and clean it up.

Cheers,
Tom

Member Avatar for tcstom

I just found the solution, no thanks to you guys :(, but i thought I would share anyway.

Change
Line#23

InstallFromDeviceList(DeviceList);

To

InstallFromDeviceList(&DeviceList);

Change
Line#28#

int AddFromDevicelist(CLinkedList<Device> DeviceList)

To

int AddFromDevicelist(*CLinkedList<Device> DeviceList)

And change all the references to functions in the DeviceList Class such as:

CurrDev=DeviceList.getFirstElement();

To

CurrDev=DeviceList->getFirstElement();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.