Well, it's not a good idea to use "std" as a name, since there's a C++ namespace already called that. I took the liberty of renaming your struct as "node".
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
#include <iostream>
#include<conio.h>
struct node
{
int marks;
node *next;
};
void trave(node *start)
{
node * ptr;
ptr=start;
while (ptr!=NULL)
{
std::cout << (ptr->marks);
ptr = ptr->next;
std::cout << std::endl;
}
}
int main()
{
clrscr();
node *s, *start,*ptr;
start = s;
s = new node;
s->marks = 300;
s->next = ptr;
ptr = new node;
ptr->marks = 450;
ptr->next = ptr;
ptr = new node;
ptr->marks = 444;
ptr->next = NULL;
s->next->next = ptr;
trave(start);
getch();
}
|
There are uninitialised and incorrectly-used pointers here.
Line 29:
start = s;
- none of the variables have been initialised at this point, so this line is not useful, it just replaces one garbage value with a different garbage value.
Line 34:
s->next = ptr;
s is a good (valid) pointer. but ptr still is uninitialised, so this is not a good move. It means s->next now contains garbage.
Line 41:
ptr = new node;
ptr has already contained the address of a new node. It should have been deleted before this line. Now the previous value is lost and there is a memory leak.
Line 45:
s->next->next = ptr;
Remember line 34? And the fact that s->next contains garbage. Well, attempting to access memory using that pointer is not allowed, so this instruction must fail.
I didn't get any further than that. But the main thing is to make sure all pointers are valid before trying to use them. And always pair the use of the
new
operator with a corresponding
delete
of the same pointer to de-allocate the memory when finished.