我有一个代码来实现链表它工作正常。我想在链接列表中包含一个字符串,但是当我添加字符串时,我遇到运行时错误,当程序到达此行时崩溃:
new_node->name = "hello";
完整的代码:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
struct list_item
{
int key;
int value;
string name;
list_item *next;
};
struct list
{
struct list_item *first;
};
int main()
{
//Just one head is needed, you can also create this
// on the stack just write:
//list head;
//head.first = NULL;
list *head = (list*)malloc(sizeof(list));
list_item *new_node = NULL;
head->first = NULL;
for(int i = 0; i < 10; i++)
{
//allocate memory for new_node
new_node = (list_item*)malloc(sizeof(list_item));
//adding the values
new_node->key = i;
new_node->name = "hello";
new_node->value = 10 + i;
//if the list is empty, the element you are inserting
//doesn't have a next element
new_node->next = head->first;
//point first to new_node. This will result in a LIFO
//(Last in First out) behaviour. You can see that when you
//compile
head->first = new_node;
}
//print the list
list_item *travel;
travel = head->first;
while(travel != NULL)
{
cout << travel->value << endl;
cout << travel->name << endl;
travel = travel->next;
}
//here it doesn't matter, but in general you should also make
//sure to free the elements
return 0;
}
任何人都可以帮助我如何在c ++中以正确的方式包含字符串?
答案 0 :(得分:3)
你混合C
和C++
使用其中任何一个。而不是malloc
使用new
来分配内存。
只需使用
new_node = new(list_item);
而不是
new_node = (list_item*)malloc(sizeof(list_item));
,最后通过调用delete
请勿使用malloc
,因为它不会初始化内存。要检查只需运行g++ -g -Wall -fdump-tree-gimple test.cpp
并打开vim test.cpp.004t.gimple
并找到malloc()
行,就会显示
new_node = malloc (16); /* allocated using malloc i.e not initialized */
D.21870 = &new_node->name; /* base address of string data type 'name' */
std::basic_string<char>::operator= (D.21870, "hello"); /* it causes the seg. fault */
要了解详情,请参阅此In what cases do I use malloc vs new?