-2
URI 1463
I’m solving URI Exercise 1464 (Link to the Exercise), and I had the problem of "Segmentation fault (core dumped)" and I can’t locate the root of the error (I know it might be in the realloc/malloc
).
Below is the following 1463 code in cpp:
#include <iostream>
#include <string>
#include <queue>
using namespace std;
typedef struct no
{
char info;
struct no *left;
struct no *right;
} Node;
typedef struct treeBin
{
Node *root;
} treeBin;
string removeSpace(string input)
{
string phrase;
int cont, aux = 0;
for (cont = 0; cont < input.length(); cont++)
{
if (input[cont] != ' ')
{
phrase.push_back(input[cont]);
}
}
return phrase;
}
Node *createNode(string input, int first, int end)
{
int cont = 0, cont_parent = 0, separator = 0;
char carac = ' ';
Node *node = (Node *)realloc(node, sizeof(Node));
if (first == end)
{
node->right = NULL;
node->left = NULL;
node->info = input[first];
}
else
{
if ((input[first] == '(') && (input[end] == ')'))
{
node = createNode(input, first + 1, end - 1);
}
else
{
for (cont = first; cont <= end; cont++)
{
if (input[cont] == '(')
{
cont_parent++;
}
else if (input[cont] == ')')
{
cont_parent--;
}
else if (input[cont] == '+' || input[cont] == '-')
{
if (cont_parent == 0)
{
separator = cont;
carac = input[cont];
}
}
else if (input[cont] == '/' || input[cont] == '*')
{
if (cont_parent == 0 && (carac != '+' && carac != '-'))
{
separator = cont;
carac = input[cont];
}
}
}
node->info = carac;
node->left = createNode(input, first, separator - 1);
node->right = createNode(input, separator + 1, end);
}
}
return node;
}
void printLine(queue<Node *> row, int currentLevel)
{
queue<Node *> aux;
if (row.empty())
{
return;
}
else
{
cout << "Nivel " << currentLevel << ": ";
while (!row.empty())
{
cout << row.front()->info;
if (row.front()->left != NULL)
{
aux.push(row.front()->left);
}
if (row.front()->right != NULL)
{
aux.push(row.front()->right);
}
row.pop();
}
cout << endl;
printLine(aux, currentLevel + 1);
}
}
void printTree(treeBin *binTree)
{
queue<Node *> aux;
aux.push(binTree->root);
printLine(aux, 0);
}
main()
{
string input;
treeBin *binTree = new treeBin;
getline(cin, input);
do
{
input = removeSpace(input);
cout << input << endl;
binTree->root = createNode(input, 0, input.length() - 1);
printTree(binTree);
getline(cin, input);
if (!cin.eof())
cout << endl;
} while (!cin.eof());
return 0;
}
Thank you William, but still presenting Segmentation Fault in Debugger and URI, (in the same line
Node *node = new Node;
)– KsZiN
Strange, the code works in g++ 8.1.0. surely has something to do with the compiler version used.
– William Kennedy