I'm writing a program in C++ to convert a user-submitted string into a postfix expression and then evaluate it. The function where the string is tokenized into operands, operators and such looks like this:

void Calc::tokenize(char * s){
        cout << s << endl;
        int i = 0;
        char * t = new char[2];
        while (i < strlen(s)){
                *t = *(s+i);
                *(t+1) = '\0';
                cout << t;
                cout << i << endl;
                if (*t == ' '){
                cout << t;
        //other stuff here

I determined from putting cout statements in various places that the program segfaults at the if (*t == ' ') line, but I can't understand why. I was having other problems with this code (apparently with managing parentheses at the point of organizing into postfix, I might ask about that later) but this one is suddenly in the way of everything. Any ideas?

Edited by gwjunkie: clarifying

6 Years
Discussion Span
Last Post by gwjunkie

Doesn't seem to be letting me edit the OP now.

Anyway, I'm now getting segfaults at the int i = 0 line. Why would it do that? =/


Hard to tell from the limited amount of code you posted, but
1 - are you sure that the array that you're passing in as s is null-terminated?

2 - t points to an array of only 2 chars. Does s always point to a 2-char array (including the null char)?


1. s was always null terminated as it's designed to take it through cin.
2. doesn't matter, I only take the character at index i from s, and place that in t.

The issue, according to my professor, was that I wasn't flushing cout with endl or flush(cout). So oops.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.