Error reading characters of string error in malloc()ed object. Why?

Viewed 218

I'm working with C++ in Visual Studio.
I have a problem when using this structure:

struct TreeNode
{
    string info;
    TreeNode* left, * right;
};
typedef struct TreeNode* ExpTree;

like in this function:

ExpTree createNode(string info)
{
    TreeNode* temp;
    temp = (TreeNode*)malloc(sizeof(TreeNode));
    if (temp == NULL)
    {
        cout << "Out of space!\n";
        return (temp);
    }
    temp->left = NULL;
    temp->right = NULL;
    temp->info = info;
    return temp;
};

When I try to run this in the main function:

ExpTree tree = NULL;
tree = createNode(expresie);
cout << tree->info;

it prints nothing and exits with this code: -1073741819.

After debugging I saw that the program stops on this line: temp->info = info;, saying <Error reading characters of string>.

I made a little research on this and I saw that this has to do more with a bad design of the code, and not with a certain problem with a single solution.

So what did I do wrong here?

2 Answers

I think that the proposed duplicate technically does answer the question.
But here is some specifics on how that explains the problem here.

C "strings", which is not actually a thing there, are only memory containing char, usually terminated with '\0'. What ever is done with them, is done by functions which expect nothing but chars in memory.

C++ std::strings are different, they are objects, with methods, overloaded operators etc.
They do need initialisation or will fail in almost all use cases, like you have observed.

The init is done with new() not with malloc().
That is why you should use new() and why (as you have confirmed by now) it solves your problem.

Here is the solution. Use following code:

TreeNode* temp = new TreeNode();
//temp = (TreeNode*)malloc(sizeof(TreeNode));

Now the explanation. malloc only allocates memory of the size specified. It does not initializes it. In your case when you use string in the structure it is a class which needs initialization and without proper initialization the behavior of assignment is undefined.

using new is reconnended because it makes sure that not only the structure but all its components inclusing string info; gets initialized properly.

Related