views:

47

answers:

2

Hey guys, i'm working on a program that gets a postfix expression and calculates it..

I have two functions:

  1. Converts infix to postfix
  2. Calculate the postfix

When I try small expressions, like 1+1 or (1+1)*1, it works fine but when i use all the operands I get something nasty,

Here is the example: 2*2/2+1-1 gets something like: 222/*11-+T_CHECKÖÐ7?█Ã

If you see, the expression is right until the 'T'

I believe it's some parameter mistake, so i'll put the header and return values here

1st)

char* convert(char *infix);
char *post = (char *)malloc(sizeof(char)*tamP);
return post;

2nd)

int evaluate(char *postfix)
while (*postfix != '\0')
return result;

Caller)

char* post = convert(infix);
result = evaluate(post);

Thanks

+4  A: 

That kind of weird string looks more like a buffer overflow error. You are likely overwriting the null-terminator, so when the string is printed (or later used), it keeps going until it finds one, examining random program memory until it gets there.

Check that all of your string manipulations are correct.

Jonathan
+1  A: 

It is possible that you are not adding the '\0' character at the end of 'post' (after the last sensible character) in the convert(char*) function. That's one reason I can think of. Try setting the complete string to '\0' before you do anything with it:

memset(post, 0, tamP);

should do.

Saurabh Manchanda
It almost did the thing, but you lead me on the right question, i don't know why, but when the stack finished putting the operands, on the last one the string got those wierld stuff, then i put an '\0' when the stack finishes putting the operands and worked! thks
Guilherme