Thread: [C++] Segmentation Fault {Novice C++ Programmer}

  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    93

    [C++] Segmentation Fault {Novice C++ Programmer}

    Hello folks.

    In the following function, cleanSpace [which takes in a string such as
    Code:
    this      is\ta\ta          a        test
    . It cleans it up. I am recieving a segmentation fault on one line when I apply it to a second program [my second school assignment]. I do not understand what the problem is here.

    Problem is on the bolded line.

    Code:
    int Account::cleanSpace(char c[])
    {
        int i=0,
            j=0,
            k=0, 
            m=0; 
            
       /* Ultimately this loop will scan for new lines and tabs and replace them 
       with spaces. */
        for(i=0; c[i]; i++)
        {   
    	    if(c[i] == '\n' || c[i] == '\t')
    	    c[i] = ' ';     
        }
    
       /* For loop finds character starting point. */
        for(i=0; c[i] == ' '; i++)
        {
            c[m] = c[i+1];
        }         
    	     
       /* For loop moves all characters next to the first found character. */
        for(i++; c[i]; i++)
        {
            c[++m] = c[i];
        }
    
       /* For loop removes trailing spaces. */
        for(i = strlen(c) - 1; c[i] == ' '; i--)
        {
            c[i] = '\0';
        }
    
       /*For loop removes excess spaces. */
        for(i = 0; c[i]; i++)
        {
            if(c[i] == ' ' && c[i+1] == ' ')
            {
                j = i;
                
        	    while(c[j] == ' ')
                {
    	           j++;
                } 
    	    
        	    for(k = i + 1; c[k]; k++, j++)
                {
        		      c[k] = c[j];
        	    }
            j=0;                           
    	   }
        }
        return strlen(c);
    }
    The problem is on the bolded line.

    Here is my header file, if its needed here.
    Code:
    #ifndef ACCOUNT_H
    #define ACCOUNT_H
    
    class Account
    {
          private: 
                   char customer[251];
                   char accountNumber[16];
                   int balance;
          public:
                   Account(){init(",,,;","000000000000000",0);} //Default constructor
                   Account(char c[], char num[], int b){init(c, num, b);} //Overloaded constructor
                   void init(char c[], char num[], int b); //Initialization function
                   int cleanSpace(char c[]); //Cleanspace function
                   int changeCustomerInfo(char c[]); //Change customer info
                   void changeAccountNumber(char num[]){strcpy(this->accountNumber, num);}
                   void changeBalance(int b){this->balance = b;}
                   void getLastName(char st[]); //Retrieves the last name
                   void getFirstName(char st[]); //Retrieves the first name
                   void getCity(char st[]); //Retrieves the city name
                   void getPhoneNumber(char st[]); //Retrieves the phone number
                   const char* getCustomer() const{return customer;}
                   const char* getAccountNumber() const{return accountNumber;}
                   int getBalance()const{return balance;}
                   ~Account(){} //Destructor
    };
    #endif
    I would appreciate any help, and thanks in advance.

  2. #2
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    Maybe you are passing in a char array that's not zero terminated. You will have to run it through the debugger to see whats going on.

    Also, a better solution might be to pass in the size as well. Passing in the buffer your way is consider a major security hole.

  3. #3
    Registered User
    Join Date
    May 2005
    Posts
    73
    you know if you used a temp character array in your cleanup function you could probably reduce your code to one for loop with a couple of if statements. Would eliminate the need for 7 separate loops which could equal a lot of wasted time if your string is long. Would make your code more readible and rid of the potential problems with altering the array you are processing on.

    As for you problem.. sorry I can't help.. I'm a retard without the aid of my trusty debugger

  4. #4
    Registered User
    Join Date
    Nov 2004
    Posts
    93
    Function worked fine in my previous program.

  5. #5
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    Just because it worked, doesn't necessarily mean it was right. Post the code that is calling this function.

  6. #6
    Registered User
    Join Date
    Nov 2004
    Posts
    93
    Code:
    #include <stdio.h>
    #include <string.h>
    #include "Account.h"
    #include "Account.cpp"
    
    int initTest(Account& a, Account& b);
    int test1(Account& in);
    void test2(Account& in);
    void test3(Account& in);
    void test4(Account& in);
    void message();
    
    int main()
    {
    	Account one;
    	if (test1(one))
    	{
    		char d[] = "   xxxxx  xxxxxxxxxxxxxxxxxxx"
    				   "xxxxxxxxxxxxxxxxxxxxxxxxx"
    				   "xxxxxxxxxxxxxxxxxxxxxxxxx"
    				   "xxxxxxxxxxxxxxxxxxxxxxxxx"
    				   "xxxxxxxxxxxxxxxxxxxxxxxxx"
    				   "xxxxxxxxxxxxxxxxxxxxxxxxx"
    				   "xxxxxxxxxxxxxxxxxxxxxxxxx"
    				   "xxxxxxxxxxxxxxxxxxxxxxxxx"
    				   "xxxxxxxxxxxxxxxxxxxxxxxxx"
    				   "xxxxxxxxxxxxxxxxxxxxxxxxx"
    				   "xxxxxxxxxxxxxxxxxxxxxxxxx";
    		char num[] = "aw0000000000000"; 
    		Account two(d, num, 5347);
    		Account three;
    		three.init(d, num, 5347);
    		if (initTest(two,three))
    		{
    			 printf("Failed init test\n"
    					"fix your init function\n");
    		}
    		else
    		{
    			test2(two);
    		}
    	}
    	return 0;
    }

  7. #7
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    Ok and how about the code that calls: Account::cleanSpace(char c[])

  8. #8
    Registered User
    Join Date
    Nov 2004
    Posts
    93
    Code:
    int Account::changeCustomerInfo(char c[])
    {   
        int result = 0;
        char temp[251];
        result = strlen(c) - 250; 
    
        cleanSpace(c); //Calls the cleanSpace function
             
        if(strlen(c) <= 250){
               strcpy(this->customer, c);
        }    
            else{
                for(int i = 0; i < 250; i++){
                        temp[i] = c[i];
                }
            strcpy(this->customer, temp);}
                 
            if(strlen(c) > 250){
                return result;}
                
            else return 0;  
    }

  9. #9
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    Ok, this is getting silly, I am trying trace your array through your program, from where it gets handed to your class in main to where it gives you the error in cleanspace ...so now lets see what calls changeCustomerInfo() and any other calls as well in between so that I can trace it the whole way through.

  10. #10
    Registered User
    Join Date
    Nov 2004
    Posts
    93
    Ok, I also discovered the problem [as via asking my professor]. He told me it may because I am being passed a string literal. The function is working on the string and cleaning it when it is already clean. The function is acting on a string that does not need changing.

    To fix this issue, I am confused.

  11. #11
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by INFERNO2K
    Ok, I also discovered the problem [as via asking my professor]. He told me it may because I am being passed a string literal. The function is working on the string and cleaning it when it is already clean. The function is acting on a string that does not need changing.

    To fix this issue, I am confused.
    Don't use the string literal directly in your program, copy it into an array or to a pointer you've allocated memory for.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  12. #12
    Registered User
    Join Date
    Nov 2004
    Posts
    93
    so at the begining of cleanspace, I would declare a temp array and set it to st, and work on the temp array?

  13. #13
    Registered User
    Join Date
    Nov 2004
    Posts
    93
    This is how I call changeCustomerinfo.

    Looks like a problem the more I look at it
    Code:
    void Account::init(char c[], char num[], int b)
    {
         changeCustomerInfo(c);       
         changeAccountNumber(num);
         changeBalance(b);
    }

  14. #14
    Registered User
    Join Date
    Nov 2004
    Posts
    93
    Yeah that is forsure the problem.

    I am acting on a string literal

  15. #15
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Changing the use of a string literal so it doesn't break your code could be as easy as changing something like this:
    Code:
    void func(char *cptr)
    {
        // Do something with cptr
    }
    
    int main()
    {
        func("Hello");  // "Hello" is a string literal
        return 0;
    }
    .. to this:
    Code:
    void func(char *cptr)
    {
        // Do something with cptr
    }
    
    int main()
    {
        char data[] = "Hello";  // data is not a string literal
        func(data);  // Use char array instead of the string literal    
        return 0;
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 05:04 PM
  2. Segmentation fault
    By NoUse in forum C Programming
    Replies: 4
    Last Post: 03-26-2005, 03:29 PM
  3. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 01:33 PM
  4. Segmentation fault...
    By alvifarooq in forum C++ Programming
    Replies: 14
    Last Post: 09-26-2004, 12:53 PM
  5. Rtfm
    By XSquared in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 03-13-2003, 05:19 PM