【发布时间】:2021-04-13 00:52:53
【问题描述】:
我正在 Visual Studio 中使用 C++。
我在使用这个结构时遇到了问题:
struct TreeNode
{
string info;
TreeNode* left, * right;
};
typedef struct TreeNode* ExpTree;
喜欢这个函数:
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;
};
当我尝试在主函数中运行它时:
ExpTree tree = NULL;
tree = createNode(expresie);
cout << tree->info;
它不打印任何内容并使用以下代码退出:-1073741819。
调试后我看到程序停在这一行:temp->info = info;,说<Error reading characters of string>。
我对此进行了一些研究,发现这更多地与糟糕的代码设计有关,而不是与单一解决方案的某个问题有关。
那么我在这里做错了什么?
【问题讨论】:
-
你为什么在这里使用
malloc?malloc只会分配内存,不会初始化任何类。使用new代替,甚至更好的是标准容器和智能指针。 -
嗨@churill,这似乎足以做出回答,不是吗?
-
@Yunnosch 可能,但同时我也经常看到这个错误。我相信它可能有一个很好的副本。
-
这能回答你的问题吗? What is the difference between "new" and "malloc" and "calloc" in C++? 和 this 也是相关的。
-
我认为它可以回答。但我怀疑任何首先使用
malloc()的人可能会问“如果这有区别,那我为什么需要在我的代码中使用它?”。
标签: c++