我有一个代码来实现链接列表,它可以正常工作。我想在链接列表中加入一个字符串,但是当我添加字符串时,我的运行时间错误崩溃了该行:
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 中以正确的方式包括一个字符串?
您混合了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 */
要获得更多信息,请在什么情况下使用Malloc vs New?