473,695 Members | 2,477 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reading in a file into a Linked List - Segmentation Fault

Hello,

I'm trying to read data from a file and then insert that into a linked
list. The way I have it, the program compiles, however, I'm getting a
segmentation fault error message when I run the program. I'm fairly new
at the pointer business, and I'd appreciate any advice. Here's my code:

int main()
{
ifstream fin;
Fish fishy;
FishLinkedList lake;

fishy.readFishD ata(fin);
while (!fin.fail()) {
lake.insertAtHe ad(fishy);
fishy.readFishD ata(fin);
}

fin.clear();
fin.close();

}

void Fish::readFishD ata(istream &sin) {
getline(sin, type, '/');
sin >> weight;
sin.ignore(80, '\n');
}

void FishLinkedList: :insertAtHead(F ish fishy)
{
if (head != NULL) { // there is a list
Fish *temp = head;
Fish *insertMe = &fishy;
temp->setNext(insert Me);
} else {
head = &fishy;
}
}

Thanks!

Frank

Jul 22 '05 #1
3 2961
"Francis Bell" <ph**********@c harter.net> wrote...
I'm trying to read data from a file and then insert that into a linked
list. The way I have it, the program compiles, however, I'm getting a
segmentation fault error message when I run the program. I'm fairly new
at the pointer business, and I'd appreciate any advice. Here's my code:

int main()
{
ifstream fin;
Fish fishy;
FishLinkedList lake;

fishy.readFishD ata(fin);
while (!fin.fail()) {
lake.insertAtHe ad(fishy);
fishy.readFishD ata(fin);
}

fin.clear();
fin.close();

}

void Fish::readFishD ata(istream &sin) {
getline(sin, type, '/');
sin >> weight;
sin.ignore(80, '\n');
}

void FishLinkedList: :insertAtHead(F ish fishy)
This function accepts its argument _by_value_. That is, when
the function is called a _temporary_ object is created. It
lives only until the function returns (and that's important).
{
if (head != NULL) { // there is a list
Fish *temp = head;
Fish *insertMe = &fishy;
Here you take an address of the temporary value.
temp->setNext(insert Me);
Here you store that address.
} else {
head = &fishy;
Here you store the address of the temporary in the 'head'
variable (that you hope will be valid next time around).
It will NOT.
}
}


You need either to set up your list (which, BTW, you never
showed) to store the _values_ of those fishes, not _pointers_,
or, if you insist on storing pointers, you gotta store the
addresses of dynamically allocated objects.

I recommend the first approach, it's easier. The second one
will require some kind of clean-up (for freeing that memory)
which in itself can take all fun out of studying pointers.

Victor
Jul 22 '05 #2
Victor Bazarov wrote:
"Francis Bell" <ph**********@c harter.net> wrote...
I'm trying to read data from a file and then insert that into a linked
list. The way I have it, the program compiles, however, I'm getting a
segmentatio n fault error message when I run the program. I'm fairly new
at the pointer business, and I'd appreciate any advice. Here's my code:

int main()
{
ifstream fin;
Fish fishy;
FishLinkedList lake;

fishy.readFishD ata(fin);
while (!fin.fail()) {
lake.insertAtHe ad(fishy);
fishy.readFishD ata(fin);
}

fin.clear();
fin.close();

}

void Fish::readFishD ata(istream &sin) {
getline(sin, type, '/');
sin >> weight;
sin.ignore(80, '\n');
}

void FishLinkedList: :insertAtHead(F ish fishy)

This function accepts its argument _by_value_. That is, when
the function is called a _temporary_ object is created. It
lives only until the function returns (and that's important).

{
if (head != NULL) { // there is a list
Fish *temp = head;
Fish *insertMe = &fishy;

Here you take an address of the temporary value.

temp->setNext(insert Me);

Here you store that address.

} else {
head = &fishy;

Here you store the address of the temporary in the 'head'
variable (that you hope will be valid next time around).
It will NOT.

}
}

You need either to set up your list (which, BTW, you never
showed) to store the _values_ of those fishes, not _pointers_,
or, if you insist on storing pointers, you gotta store the
addresses of dynamically allocated objects.

I recommend the first approach, it's easier. The second one
will require some kind of clean-up (for freeing that memory)
which in itself can take all fun out of studying pointers.

Victor

Thanks Victor! I kind of understand what you are saying...with one
glaring exception. You said I need to set up my list to store the
values of those fishes; I honestly that that was what I was doing with
this insert function. I thought I was creating a list and inserting
each fishy that gets read in into the front position of the list. I'm
simply drawing a blank on what I need to do here.

Frank

Jul 22 '05 #3
"Francis Bell" <ph**********@c harter.net> wrote...
Victor Bazarov wrote:
"Francis Bell" <ph**********@c harter.net> wrote...
I'm trying to read data from a file and then insert that into a linked
list. The way I have it, the program compiles, however, I'm getting a
segmentatio n fault error message when I run the program. I'm fairly new
at the pointer business, and I'd appreciate any advice. Here's my code:

int main()
{
ifstream fin;
Fish fishy;
FishLinkedList lake;

fishy.readFishD ata(fin);
while (!fin.fail()) {
lake.insertAtHe ad(fishy);
fishy.readFishD ata(fin);
}

fin.clear();
fin.close();

}

void Fish::readFishD ata(istream &sin) {
getline(sin, type, '/');
sin >> weight;
sin.ignore(80, '\n');
}

void FishLinkedList: :insertAtHead(F ish fishy)

This function accepts its argument _by_value_. That is, when
the function is called a _temporary_ object is created. It
lives only until the function returns (and that's important).

{
if (head != NULL) { // there is a list
Fish *temp = head;
Fish *insertMe = &fishy;

Here you take an address of the temporary value.

temp->setNext(insert Me);

Here you store that address.

} else {
head = &fishy;

Here you store the address of the temporary in the 'head'
variable (that you hope will be valid next time around).
It will NOT.

}
}

You need either to set up your list (which, BTW, you never
showed) to store the _values_ of those fishes, not _pointers_,
or, if you insist on storing pointers, you gotta store the
addresses of dynamically allocated objects.

I recommend the first approach, it's easier. The second one
will require some kind of clean-up (for freeing that memory)
which in itself can take all fun out of studying pointers.

Victor

Thanks Victor! I kind of understand what you are saying...with one
glaring exception. You said I need to set up my list to store the
values of those fishes; I honestly that that was what I was doing with
this insert function.


What does 'setNext' do? Doesn't it simply copy the address into some
kind of 'next' member? So, it's not storing _values_, it's storing
_addresses_ of values.
I thought I was creating a list and inserting
each fishy that gets read in into the front position of the list.
You were? Well, you might have been, we couldn't see what you did
there since you didn't post the code that actually does the storing.
I'm
simply drawing a blank on what I need to do here.


Your 'FishLinkedList ' is based on storing pointers to 'Fish' objects
(at least that's what it seems to be doing judging from the source,
since you didn't provide the definition and implementation of the
FishLinkedList class). Supposedly, it looks something like this:

class FishLinkedList {
Fish *head; // you have a pointer here
FishLinkedList *next;
public:
FishLinkedList( ) : head(NULL) {}
void setNext(Fish* pfish);
};

What you need to do here is something like

class FishLinkedList {
Fish value; // actual value, not a pointer
bool has_head;
FishLinkedList *next;
public:
FishLinkedList( ) : has_head(false) {}
void insert(Fish newvalue);
};

The problem, of course, is that it's basically impossible to value-
based storage unless you allocate all the storage before the program
begins:

class FishLinkedList {
Fish storage[100];
int tail; // where to insert
public:
FishLinkedList( ) : tail(0) {}
void insert(Fish newvalue) {
if (tail == 100) throw "list is full";
storage[tail++] = newvalue;
}
};

simply because if you don't, you have to fall back on dynamic
allocation of the storage, which presents the same set of problems
that you already faced: pointers.

Find a good book on data structures, a good book on C++ (which will
probably contain some common data structures with examples), and
give it a good read. It is really impossible to present you with
all the material on pointers, dynamic allocation, linked lists,
lifetime of objects, etc. in one newsgroup conversation.

V
Jul 22 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
3177
by: fudmore | last post by:
Hello Everybody. I have a Segmentation fault problem. The code section at the bottom keeps throwing a Segmentation fault when it enters the IF block for the second time. const int WORDS_PER_LINE = 4; when counter == 7 is when the string Concatenation fails within the IF block.
1
1135
by: Yesim | last post by:
Hello, I am trying to read two-dimensional float data into C++, but am getting a segmentation fault error message. This happens in g++ compiler versions 2.95.2 and 3.1, but not on version 3, each in three different servers. I need to compile in the latest version. Below I attach the beginning of the code giving the problem: # include <iostream> # include <fstream>
18
26104
by: Digital Puer | last post by:
Hi, I'm coming over from Java to C++, so please bear with me. In C++, is there a way for me to use exceptions to catch segmentation faults (e.g. when I access a location off the end of an array)? Thanks.
27
3351
by: Paminu | last post by:
I have a wierd problem. In my main function I print "test" as the first thing. But if I run the call to node_alloc AFTER the printf call I get a segmentation fault and test is not printed! #include <stdlib.h> #include <stdio.h> typedef struct _node_t {
4
3790
by: scythemk | last post by:
Hi, I am writing a program that, everytime it executes, first loads all information from a file into a linked list of nodes, using struct to define it. After manipulating the data and receiving user input, the program once again outputs the linked list information to the same file. My problem is that when I'm first trying to get the info from the file into the linked list I get a bus error. My code is as follows: struct nodeType {...
4
4281
by: FBM | last post by:
Hi, I am working on a program that simulates one of the elements of ATM. The simulation stores events which occurs every some milliseconds for a certain amount of time. Every time that an event is stored in a double linked list, the whole list is sorted for the next round. My problem appears when subjecting the program to heavy load, that is, when I run the simulation for more than 10,000 miliseconds (every event occurs in...
7
6099
by: utab | last post by:
Hi there, I am trying to read from a file and at the same time change certain fields of the same field, there are 6 fields in this file like 1 2 3 4 5 6 --------/--------/--------/--------/--------/--------/ // field_width=8 For example, I position my file pointer at the begining of the 4th fileld lets say 25th character(3*(field_width)+1) and when I try to
116
4580
by: dmoran21 | last post by:
Hi All, I am working on a program to take input from a txt file, do some calculations, and then output the results to another txt file. The program that I've written compiles fine for me, however, when I run it, it stalls and does nothing. I'm wondering if there's something obvious that I'm missing. My code is below and any help would be appreciated. Thanks, Dave
6
2142
by: mattmao | last post by:
Okay, this is just my exercise in order to prepare for the coming assignment regarding the damned Linked List issue... The task is simple and I am about to finish it. However, I couldn't go around one last bit: how to print out the elements? Here is so far what I've got: #include <stdio.h> #include <stdlib.h> struct intRecord
0
8585
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9132
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8864
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7682
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5842
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4351
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4592
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3024
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2288
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.