Run-time issue

Hi,

I'm writing a simple link-listed object but I'm getting a runtime error (memory reading)

I am relatively new to programming and I've looked through the code and I cannot spot anything that would cause any problems, that's probably just pipe-vision and one of you guys will spot the problem straight away.

Thanks!

cNode.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#pragma once
#include "Includes.h"
class cNode
{
private:
	cNode* mpNext;
	int mObjectNumber;
public:
	cNode(int ObjectNumber);
	~cNode(void)
	{
		printf("Deleting node %d\n",mObjectNumber);
	}
	void AddLink(cNode *WhereToPoint)
	{
		mpNext = WhereToPoint;
	}
	int GetObjNum()
	{
		return mObjectNumber;
	}
	cNode *GetNextPtr()
	{
		return mpNext;
	}
};

cNode.cpp
1
2
3
4
5
6
7
8
9
#include "cNode.h"

cNode::cNode(int ObjectNumber)
{
	printf("Constructor called for node %d\n",ObjectNumber);

	mpNext = 0;
	mObjectNumber = ObjectNumber;
}

Main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include "Includes.h"
#include "cNode.h"

using namespace std;

void main()
{
#define LIST_LEN 5

	cNode	*pHead		= NULL;
	cNode	*pCurrent	= NULL;
	cNode	*pNode;
	int		ObjNum		= 0;

	for (int i = 0; i < LIST_LEN; i++)
	{
		pNode = new cNode(ObjNum++);

		if(!pHead)
		{
			pHead = pNode;	
		}
		else
		{
			pCurrent->AddLink(pNode);
			pCurrent = pNode;
		} 
	}
}
Line 25, when pCurrent == NULL.
Thanks Peter87, now another problem I have is that during run-time 'pCurrent' is being used without being initialized. I know why, but I am confused as to why I have been given this code on my University course inside a 300+ page "Advanced Programming with C++" course book given to me by my tutor.

Is this code viable? will it actually work the way it has been illustrated here give or take a few changes to code?

This is the changed code.

Main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include "Includes.h"
#include "cNode.h"

using namespace std;

void main()
{
#define LIST_LEN 5

	cNode	*pHead		= NULL;
	cNode	*pCurrent;
	cNode	*pNode;
	int		ObjNum		= 0;

	for (int i = 0; i < LIST_LEN; i++)
	{
		pNode = new cNode(ObjNum++);

		if(!pHead)
		{
			pHead = pNode;	
		}
		else
		{
			pCurrent->AddLink(pNode);
			pCurrent = pNode;
		} 
	}
}
Thanks anyway but I found out why It wouldn't have worked;

I wasn't setting pCurrent to point at pNode if the pNode was the 'Head' (Starting) node for the list.
Topic archived. No new replies allowed.