Problem with Entering String Data into a Node

Write your question here.
I am trying to enter string data into a struct Node but the program bombs. I suspect it is line 60 causing the crash. Why so?


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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
*	Chapter 15 Problem 3
*
*	Write a program to find an element in a linked list by name
*
*
*/

#include <iostream>
//#include <string>
#include "c15p3.h"

using namespace std;
// Function Prototypes
void addTail(LinkedList* list, string data);
void displayLinkedList(LinkedList* list);
void initializeList(LinkedList* list);

int main()
{
	// Declare and initialize variables
	char fName[15];
//	char* p_fName = fName;
	int choice = 0;
	LinkedList linkedList;
	initializeList(&linkedList);

	while (true)
	{
		// Print Menu
		cout << "Menu:" << endl <<
			'\t' << "0. Exit" << endl <<
			'\t' << "1. Add a node " << endl <<
			'\t' << "2. Display node(s) " << endl << endl;

		cout << "Select a number from the Menu: ";
		cin >> choice;

		switch (choice)
		{
		case 0:
			return 0;
		case 1:
			cout << "Please enter your first name: ";
			cin >> fName;
			cout << "Name is " << fName << endl;
			addTail(&linkedList, fName);
			break;
		case 2:
			displayLinkedList(&linkedList);
			break;
		}
	}
}


void addTail(LinkedList* list, string data)
{
	Node* node = (Node*)malloc(sizeof(Node));
	node->name = data;
	if (list->head == NULL)
	{
		list->head = node;
		node->next = NULL;
	}
	else
	{
		list->tail->next = node;
	}
	list->tail = node;
}


void initializeList(LinkedList* list)
{
	list->head = NULL;
	list->tail = NULL;
	list->current = NULL;
}


void displayLinkedList(LinkedList* list)
{
	cout << endl << "Linked List \n";
	Node* current = list->head;
	while (current != NULL)
	{
		cout << current->name << endl;
		current = current->next;
	}
}
If Node::name is a std::string type, you have bypassed the construction mechanism by using the C function malloc so that line 60 invokes a member method of an invalid object.

Prefer to use new/delete in C++ rather than malloc/free
Made the change. Found another bug. Corrected it. Program works. Now to program rest of problem.

Thank you, cire. I am amazed that there is a difference between malloc and new. I just thought they were the same things used for dynamic memory allocation..
Topic archived. No new replies allowed.