Thread: Found a seg fault, but can't explain why i get it

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    719

    Found a seg fault, but can't explain why i get it

    i'm having a problem with a seg fault, but i'm stumped.
    i've found it, but i just do not understand why i get it.
    it's in the seventh line of WordTree::insert(const string &).
    i have put similar code in the third, fourth and fifth line of main()
    and that code doesn't seg fault.

    (don't worry, you don't have to count the lines, i have marked them with "//******" and a description)

    Code:
    /*** COMNDENSED TO SAVE SPACE ***/
    
    #ifndef WORDTREE_H
    #define WORDTREE_H
    #include <string>
    #include <iostream>
    using std::cout;
    using std::endl;
    class WordTree
    {
    	typedef std::string str;
    	public:
    	WordTree(const str & = "");
    	int search(const str &);
    	int insert(const str &);
    	void print(void);
    	private:
    	WordTree *left;
    	WordTree *right;
    	str key;
    };
    #endif
    Code:
    #include "WordTree.h"
    
    using namespace std;
    
    WordTree::WordTree(const string &src)
    {
    	key = src;
    	left = right = 0;
    }
    
    int WordTree::insert(const string &src)
    {
        if(!key.size())
        {
             key = src;
             return 1;
        }     
        
        // this seg faults    
        if(src < key){ cout << "test" << endl; }
        //*****************
        
        
        //the real code (i know i can factor this out, and it was to 
        //begin with, but i expanded it and simpified it to find the seg fault
        //...there's no need to fix or correct this code, i'm going to
        //revert to my original code. i have only posted it so no one would
        //accuse me not giving them the whole code and claim the seg fault is elsewhere.
        /*if(src < key)
        {
               if(left)
               {
                        cout << "CP 2" << endl;
                       return left->insert(src);
               }
               else{
                        cout << "CP 3" << endl;
                   left = new WordTree();
                       cout << "CP 4" << endl;
                   return left->insert(src);
               }
                   
        }else{
                  cout << "CP 2.b" << endl;
               if(right){
                        
                       return right->insert(src); 
                           cout << "CP 3.b" << endl;
               }
               else{
                        cout << "CP 4.b" << endl;
                   right = new WordTree();
                       cout << "CP 5.b" << endl;
                   return right->insert(src);
                   
               }
                   
        } */            
             
    	
     return 1;
    }
    
    
    //not even called, but if you have extra time, i'd like someone to comment on it if there's a better way (it's untested)
    
    int WordTree::search(const string &src)
    {
    	if(src == key)
    		return 1;
    	else
    		if(src <= key)
    			if(left)
    				left->search(src);
    			else
    				return 0;
    		else
    			if(right)
    				right->search(src);
    			else
    				return 0;
    	return 0;
    }
    
    //called but still segfaults whether it's called or not
    void WordTree::print(void)
    	{
             cout << key << endl;
             if(left)
                     left -> print();
             if(right)
                     right -> print();
        }
    Code:
    /********* crappy test file, no need to pick it apart *****/
    
    #include <cstdlib>
    #include <iostream>
    
    #include "WordTree.h"
    #include <string>
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        
        WordTree wt("n");
       
        wt.print();
    
        //this doesn't seg fault
        string x = "n";
        string y = "p";
        cout << (x < y) << endl;
        //*********************
        
        while(x != "stop")
        {
             cin >> x;
             wt.insert(x);
        }
        wt.print();
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    Last edited by misplaced; 08-27-2005 at 01:55 AM.
    i seem to have GCC 3.3.4
    But how do i start it?
    I dont have a menu for it or anything.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    I haven't tried stepping through your code with a debugger (and probably couldn't as you haven't actually provided code in a form which illustrates your problem), but on a superficial look couldn't find anything glaringly obvious.

    The reason that people tend to ask for SMALL but COMPLETE examples is not laziness; it is because it is almost certain that a paraphrased example like yours has had something left out that contributes to the problem(s) that are haunting you. Without that "something left out", we'd have to be mindreaders to actually provide a useful answer.

    As a general rule, if a segmentation fault occurs, the culprit is either at the line where it is reported OR somewhere in code that was executed (possibly in another function) before that line was reached.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    left = new WordTree();
    return left->insert(src);

    I see no default constructor, so I guess you have a new object with junk.
    Which means on your recursive call, your attempt to
    if(src < key)
    is working with garbage.

    It would seem to me that
    left = new WordTree(src);
    would solve both problems at the same time.

    Don't you get any warnings about calling constructors which don't exist.

    > typedef std::string str;
    This is all but useless, I mean you don't even use it in all the places you could use it.
    Additionally, it just makes the code harder to read as readers now have to remember more stuff just to interpret your code.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Sep 2004
    Posts
    719
    i'm sorry, perhaps i didn't explain this very well

    this is what "seg faults" (i have since realized it was an access violation..is that synonymous with seg fault?) :

    Code:
    int WordTree::insert(const string &src)
    { 
        
        // this is an access violation
        if(src < key){ cout << "test" << endl; }
       
    
        return 1;
    }
    *tries to say this without sounding like an ass* you are talking about code that is commented out. (which is the code i was talking about when i said "don't worry about it, i'm going to revert to my original code")





    btw, WordTree() doubles as default: declaration WordTree(const string & = "")
    Last edited by misplaced; 08-27-2005 at 03:54 AM.
    i seem to have GCC 3.3.4
    But how do i start it?
    I dont have a menu for it or anything.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    I'm done playing with people who post one lot of code, then claim something else
    *plonk*
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Sep 2004
    Posts
    719
    i posted all of the code because i knew you guys would have a hard time believing "string < string" causes a segmentation fault. i couldn't believe it myself. i thought that by posting it you could see that it was commented out, but still see what i was trying to do. as it turns out though, i haven't seen anything that says "segmentation fault". i was carelsss to assume it was a seg fault. i do, however, get a fatal runtime error. when i debug it says it says "access violation". i have run the following and have had no problems. i believe it has the same "conditions" as my original post, yet it does not cause a runtime error.

    Code:
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    class Tree
    {
       string key;
       
       public:   
       Tree(const string &s = ""){ key = s; }
       int test(const string &str)
        {
           if(str < key)
                return 1;
           return 0;
        }
    };
    
    int main(int argc, char *argv[])
    {
        Tree tree("the");
        string str = "thong";
        cout << tree.test(str) << endl; 
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    if you had actually read my original post, i did clearly specify which line of which function caused the runtime error. don't get mad because you wasted time looking at code that was commented out.
    i seem to have GCC 3.3.4
    But how do i start it?
    I dont have a menu for it or anything.

  7. #7
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    there is a default constructor. this one....

    WordTree(const str & = "");

    As it has a default value, this acts as a default constructor, so thats not the trouble and why no warnings/errors were issued about that.As its also non-explicit it also acts as a conversion constructor converting std::string into WordTree's.

    Perhaps if you zip up your project and attatch it we might be able to help more.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  8. #8
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by misplaced
    i posted all of the code because i knew you guys would have a hard time believing "string < string" causes a segmentation fault.
    I don't have a hard time believing that at all. What you obviousloy haven't grasped is a comment I made in my earlier response.

    As a general rule, if a segmentation fault occurs, the culprit is either at the line where it is reported OR somewhere in code that was executed (possibly in another function) before that line was reached.
    Assuming you are using a fairly well validated standard library, this means that your actual problem is almost certainly in code executed before the crash occurs.

  9. #9
    Registered User
    Join Date
    Sep 2004
    Posts
    719
    Quote Originally Posted by Stoned_Coder
    Perhaps if you zip up your project and attatch it we might be able to help more.
    that's it, all of it....running that code crashes (compiled with dev-c++ 4.9.9.2)....granted YOUR compiler will compile it, you should able to copy and paste it. here's a cleaned up version.

    Code:
    #include <string>
    
    class WordTree
    {
    
    	
    	public:
    	WordTree(const std::string & = "");
    	int insert(const std::string &);
    	
            private:
    	WordTree *left;
    	WordTree *right;
    	std::string key;
    	
    	
    };
    
    #endif
    Code:
    #include "WordTree.h"
    
    using namespace std;
    
    WordTree::WordTree(const string &src)
    {
    	key = src;
    }
    
    int WordTree::insert(const string &src)
    {
        if(src < key){ cout << "test" << endl; }
        return 1;
    }
    Code:
    //main.cpp
    #include <cstdlib>
    #include <iostream>
    
    #include "WordTree.h"
    #include <string>
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        
        WordTree wt("n");
        string x = "test";
        
        wt.insert(x);
      
        system("PAUSE");
        return 0;
    }
    Last edited by misplaced; 08-27-2005 at 06:31 AM.
    i seem to have GCC 3.3.4
    But how do i start it?
    I dont have a menu for it or anything.

  10. #10
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    That code as you'v given it doesn't compile, as you haven't #include'd <iostream> in either of your source files. It would also help if you didn't have a lone #endif in the header file as well.

    When I fixed those problems, the code compiled and ran cleanly (albeit not doing anything much).

    If I had to guess at the cause of your problem, it would be that you're not initialising the left and right members for instances of the WordTree class (e.g. you need to initialise them sensibly in the constructor). A side effect of that is that they might point at anything, and dereferencing them in any way will yield undefined behaviour. However, the code as you just gave it does not dereference those members.

    My interpretation of your last post is that you cleaned up the code, but have not actually run the cleaned code through a compiler to see if it exhibits your problem ....

  11. #11
    Registered User
    Join Date
    Sep 2004
    Posts
    719
    YES I HAVE! i started an entirely new project and ran THAT code...i missed the top 2 or 3 lines when i copied it, it doesn't mean i didn't run it...i'm not a ........ing moron..why would i modify code and not run it? that's stupid. how many times do i have to tell you which line causes the error? it has nothing to do with dereferencing pointers unless the error is within the string class...which i seriously doubt. i'm not some noobie looking for a quick fix. i've actually been doing c/c++ for quite some time. i am well aware of seg faults and what causes them. that is why i'm so confused by the error. i have run numerous other similar problems and have not been able to reproduce the error. the sole purpose of the last version was to show that really the only thing being done is a simple comparison.


    do you mind telling me which compiler you're using?
    i seem to have GCC 3.3.4
    But how do i start it?
    I dont have a menu for it or anything.

  12. #12
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    1) I can only interpret what you post. The code, as you posted it, did not compile. When I modified it so it compiled, it ran without an error. The only other change I made was to remove the system("PAUSE") line, as that's a non-standard function. I ran it directly from a console, so didn't need the program to pause before exiting.

    2) The compiler I tested it with last night my time was g++ 3.4.2 which came as part of a mingw distribution late last year (IIRC). My operating system is windows 2000 professional with latest service packs and applied.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Access Violation / Seg Fault
    By Korhedron in forum C++ Programming
    Replies: 31
    Last Post: 09-06-2008, 11:47 AM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. weird seg fault
    By Vermelho in forum C Programming
    Replies: 3
    Last Post: 05-10-2008, 08:27 PM
  4. unknown seg fault reason.
    By egoveneror2 in forum C Programming
    Replies: 16
    Last Post: 04-15-2008, 02:30 AM
  5. seg fault on unix platform
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 12-08-2001, 12:04 PM