GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 25-Jan-2005, 00:50
rushman8282 rushman8282 is offline
New Member
 
Join Date: Jan 2005
Posts: 2
rushman8282 is on a distinguished road
Unhappy

segmentation fault in c++


hi,
i dunno why i get this segmentation fault whenever i run the codes.
this program calculates a fully bracketed mathematical expression recursively. i.e. (1+(2*(2*4)))
can anybody tell me how to fix the segmentation fault part plz?

CPP / C++ / C Code:
#include <iostream>
#include <string>
using namespace std;

int eval(char expression[]);
int eval(char expression[])
{
	int expres_size;
	int new_expres_size;
	int bracket;
	int oper_position;
	char result;
	char interval1[100];	
	char interval2[100];

	expres_size = strlen(expression);
	
	if (expres_size == 1)
	{
		return (int)expression[0]-(int)'0';
	}

	else
	{	
		if (expression[0] == '(' )
        	{
			// taking out the brackets () by assigning to another array
                	char new_expression[expres_size-2];

	                for (int r=0; r < (expres_size-2); r++)
	                {
        	                new_expression[r] = expression[r+1];
	                }
                
			new_expres_size = strlen(new_expression);
			expres_size = new_expres_size;
			expression = new_expression;
		}
	
		bracket=0;	
	
		for (int j= 0; j < expres_size; j++)
		{
			if (expression[j] == '(' )
				bracket += 1;
			if (expression[j] == ')' )
				bracket -= 1;
			if (bracket == 0)
			{
				switch (expression[j])
				{
					case '*':
						oper_position = j;											break;	
					case '/':
						oper_position = j;
						break;
					case '+':
						oper_position = j;
						break;
					case '-':
						oper_position = j;
						break;
				}
			}
		}

		// splitting the expression character array into 2 arrays
		for (int k= 0; k < oper_position-1; k++)
		{
			interval1[k] = expression[k];
		}

		for (int p= (oper_position+1); p < expres_size; p++)	
		{
			interval2[p] = expression[p];
		}	
			
		switch (expression[oper_position])
	        {
       			case '*':
       				return (eval(interval1))*(eval(interval2)); 
	                        break;
               		case '/':
	                        return (eval(interval1))/(eval(interval2));
               		        break;
	                case '+':
               		        return (eval(interval1))+(eval(interval2));
	                        break;
               		case '-':
	                        return (eval(interval1))-(eval(interval2));
               		        break;
		}	
	}	
}

int main()
{	
	// declaring variables
	char inExpress[100];
	int str_size;
	
	// display out messages
	cout << "This program calculates a given mathematical"; 
	cout << " expression.\n";
	cout << "Please enter a mathematical expression.\n";
	cin >> inExpress;
	
	str_size = strlen(inExpress);
	cout << str_size;
	cout << "\n";

	int countBracket = 0;
	char fixExpress[str_size];

	for (int i= 0; i < str_size; i++)
	{
	//	fixExpress[i] = inExpress[i];
	
		if (inExpress[i] == '(' ) 
			countBracket += 1;

		if (inExpress[i] == ')' )
			countBracket -= 1;
	}
	
	if (countBracket != 0)
	{	
		cout << "Unmatched brackets!!\n";
		cout << "Please re-enter the expression.\n";
	}
	
	cout << eval(inExpress);	
	
	return 0;
}
Last edited by dsmith : 25-Jan-2005 at 07:34. Reason: codes corrected
  #2  
Old 25-Jan-2005, 11:42
dsmith's Avatar
dsmith dsmith is offline
Senior Member
 
Join Date: Jan 2004
Location: Utah, USA
Posts: 1,351
dsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of light
Hello rushman8282. Welcome to GIDForums™.

Your seg fault is coming because of the way that you split your strings and recall eval. You never null terminate your strings and then you are passing them back to eval at which point strlen looks for a null termination and doesn't find it until tromping all through unallocated memory. In addition your counting method was not quite right. Here is a replacement that is a bit closer:

CPP / C++ / C Code:
    int k;
    for (k= 0; k < oper_position; k++)
    {
      interval1[k] = expression[k];
    }
	interval1[k] = 0;
	cout << interval1 << "\n";
    for (int p= (oper_position+1),k=0; p < expres_size; p++,k++)
    {
      interval2[k] = expression[p];
    }
	interval2[k]=0;
	cout << interval2 << "\n";

You will notice that I added a couple of couts just to tell me what was going on. With this fix I got the rudimentary equation of 3+2 to return the proper value, but I think there are other more deep rooted problems with this routine.

My advice is to dump a bunch of print commands into this thing to try to figure out where things are going wrong.

In addition if you are using linux, I find that valgrind is an invaluable tool to track down memory leaks at exactly where they are happening.

Good luck.
  #3  
Old 26-Jan-2005, 03:38
rushman8282 rushman8282 is offline
New Member
 
Join Date: Jan 2005
Posts: 2
rushman8282 is on a distinguished road

re: segmentation fault


thank you dsmith,
i took a look and changed main algorithm.
i tested out and everything works fine except the last switch part.
all i need to do now is to call eval function recursively but not successful..
T.T what should i do??

CPP / C++ / C Code:
#include <iostream>
#include <string>
using namespace std;

int eval(char expression[]);

int eval(char expression[])
{
	int expres_size;
	int new_expres_size;
	int bracket;
	int oper_position;
	int size1;
	int size2;
	char interval1[100];	
	char interval2[100];

	expres_size = strlen(expression);
	
	if (expres_size == 1)
	{
		return (int)expression[0]-(int)'0';
	}

	else
	{	
		if (expression[0] == '(')
        	{
	                for (int r=0; r < (expres_size-2); r++)
	                {
        	                expression[r] = expression[r+1];
	                }
                	
			expres_size = expres_size-2;
		}
	
		cout << expres_size;
		cout << "\n";
				
		for (int i=0; i < expres_size; i++)
			cout << expression[i];
			
		
		// initializing bracket counter variable
		bracket = 0;
			
		for (int j= 0; j < expres_size; j++)
		{
			if (expression[j] == '(')
				bracket += 1;
			if (expression[j] == ')')
				bracket -= 1;
			if ((bracket == 0) && (expression[j] == '*'))
				oper_position = j;			
			if ((bracket == 0) && (expression[j] == '/'))
				oper_position = j;
			if ((bracket == 0) && (expression[j] == '+'))
				oper_position = j;
			if ((bracket == 0) && (expression[j] == '-'))
				oper_position = j;									
		}			
		
		
		// splitting the expression character array into 2 arrays
		for (int k = 0; k < oper_position; k++)
		{
			interval1[k] = expression[k];		
			cout << interval1[k];
		}
	
		for (int p = (oper_position+1), k = 0; p < expres_size; p++,k++)	
		{
			interval2[k] = expression[p];
			cout << interval2[k];
		}	


		switch (expression[oper_position])
	        {
     			case '*':
       				return eval(interval1)*eval(interval2); 
				break;		                        
             		case '/':
	                        return eval(interval1)/eval(interval2);
             		        break;
	                case '+':
               		        return eval(interval1)+eval(interval2);
	                        break;
               		case '-':
	                        return eval(interval1)-eval(interval2);
             		        break;
		}
	
	}
}

int main()
{	
	// declaring variables
	char inExpress[100];
	int str_size;
	
	// display out messages
	cout << "This program calculates a given mathematical"; 
	cout << " expression.\n";
	cout << "Please enter a mathematical expression.\n";
	cin >> inExpress;
	
	str_size = strlen(inExpress);
	
	int countBracket = 0;

	for (int i= 0; i < str_size; i++)
	{
		if (inExpress[i] == '(') 
			countBracket += 1;

		if (inExpress[i] == ')')
			countBracket -= 1;
	}
	
	if (countBracket != 0)
	{	
		cout << "Unmatched brackets!!\n";
		cout << "Please re-enter the expression.\n";
	}
	
	cout << eval(inExpress);
	cout << "\n";
	
	return 0;
}
Last edited by JdS : 26-Jan-2005 at 06:19. Reason: Please insert your example C/C++ codes between [c] and [/c] tags
 
 

Recent GIDBlogToyota - 2008 August Promotion by Nihal

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
problem reading to a dynamic array noamfrie C Programming Language 9 02-Jan-2005 18:35
Segmentation Fault? aaroncohn C++ Forum 2 02-Jan-2005 14:22
Why seg fault in char array? nusstu C Programming Language 11 24-Aug-2004 16:10
Need a help with C code-Segmentation Fault nkhambal C Programming Language 13 18-Jul-2004 14:58
child pid xxx exit signal Segmentation fault (11) bezak Apache Web Server Forum 1 24-Nov-2003 09:18

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 00:39.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.