C++:字符串、结构和访问冲突写入位置



我试图使用一个方法的字符串输入,并将其设置为结构的变量,然后将其放入链表中。我没有包括所有的代码,但我做了后构造函数和所有的好东西。现在代码在的线路上中断

node->title = newTitle;
node->isbn = newISBN;

所以newTitle是从我试图设置为变量节点的Book结构的title变量的方法输入的字符串。现在,我假设这与指针的问题有关,并试图为它们设置数据,但我无法找到解决方案/替代方案。此外,我尝试使用

strcpy(node->title, newTitle)

但是在将字符串转换为字符列表时出现了问题,因为strcpy只使用字符列表。还尝试了其他一些事情,但似乎都没有成功,如果能提供解释,我们将不胜感激。

struct Book
{
   string title;
   string isbn;
   struct Book * next;
};
//class LinkedList will contains a linked list of books
class LinkedList
{
 private:
     Book * head;
 public:
     LinkedList();
     ~LinkedList();
     bool addElement(string title, string isbn);
     bool removeElement(string isbn);
     void printList();
 };
 //Constructor
 //It sets head to be NULL to create an empty linked list
 LinkedList::LinkedList()
 {
     head = NULL;
 }
 //Description: Adds an element to the link in alphabetical order, unless book with 
    same title then discards
 // Returns true if added, false otherwise
 bool LinkedList::addElement(string newTitle, string newISBN)
 {
struct Book *temp;
struct Book *lastEntry = NULL;
temp = head;
if (temp==NULL) //If the list is empty, sets data to first entry
{
    struct Book *node;
    node = (Book*) malloc(sizeof(Book));
    node->title = newTitle;
    node->isbn = newISBN;
    head = node;
}
while (temp!=NULL)
{
    ... //Rest of Code

请注意,您的Book结构已经是链表实现,因此您根本不需要LinkedList类,或者您也不需要结构的"next"元素。

但是,从粘贴的最后一个(长)代码片段中,没有理由在所指示的行中出现错误。node->title=newTitle应该将newTitle中的字符串复制到结构的title字段中。字符串对象是固定大小的,因此不可能覆盖任何缓冲区并导致seg错误。

然而,你在代码的后面做的事情可能会导致内存损坏,直到以后才会导致错误。要查找的是任何可能被过度填充的数组,包括char[]。另一个想法是,您提到要保存方法参数。如果你复制,没关系,但如果你做了类似的事情

char* f() {
    char str[20];
    strcpy(str, "hello");
    return str;
}

那么你就有问题了。(因为str是在堆栈上分配的,并且只返回指向函数返回后无效位置的指针。)方法参数是局部变量。

您想要的答案可以在这里找到。

简言之:malloc返回的内存不包含正确构造的对象,因此您不能这样使用它。请尝试使用new/delete

最新更新