Linked List with Classes Segmentation Fault

Hi guys,

This is my first time posting here, so please bear with me if I don't really know how to properly ask a question here.

Basically, I need to make a stringADT linked list and I'm having trouble with my constructor.

I keep getting a Segmentation Fault when I try a simple test to see if it works.

Here is the part of the class that my test is referring to:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include "StringADT.h"

using namespace std;

StringADT::StringADT(string s)
{
  Node* nodePtr = head;
  Node* nextNode;
  int length = s.length();
  cout << length;
  for(int i = 0; i < length; i++){
    nextNode = nodePtr->next;
    nextNode->data = s.at(i);
    nodePtr = nextNode;
  }

  nodePtr = NULL;
}


Here is the call in the test:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include "StringADT.h"
#include "StringADT.cpp"

using namespace std;

int main()
{
  string s = "abcdef";
  StringADT string2();

  return 0;
}


I've never really had trouble with a Segmentation Fault before, so any tips or pointers about them for the future would also be greatly appreciated.

Thanks in advance!
closed account (zb0S216C)
It seems as though you're trying to transverse a linked-list, beginning at the head. And at each node, you're assigning the the "ith" character of "s" to the current pointed-to node's data. If this is the case, then your code can be easily simplified:

1
2
3
4
5
6
7
8
9
10
11
StringADT::StringADT( std::string PStr_ )
{
  Node *LCurrNode_;
  std::string::iterator LCurrChar_( PStr_.begin( ) );
  while( ( LCurrNode_->next ) && ( *LCurrChar_ ) )
  {
    LCurrNode_->data = *LCurrChar_;
    LCurrNode_ = LCurrNode_->next;
    ++LCurrChar_;
  }
}

I haven't tested the code yet, so I apologise in advance if it doesn't work :) Your problem is most likely the result of attempting to access an address in memory that your program doesn't own; hence the seg-fault.

Wazzak
Last edited on
Thanks!

That helped me find the problem!
Topic archived. No new replies allowed.