【问题标题】:Trying to make a Linked List that contains strings C++试图创建一个包含字符串 C++ 的链表
【发布时间】:2013-04-01 19:15:34
【问题描述】:

我目前正在处理一个链接列表,其中包含包含信息字符串的字符串。我正在使用一个看起来像这样的结构:

struct symbolTable
{
    string lexeme;
    string kind;
    string type;
    int offSet;
    symbolTable *nextSymbol;
    symbolTable *nextTable;
};

插入函数看起来有点像这样:

void MPParser::insertToSymbolTable(string identifier, string type, string kind)
{
    tempOffset++;
    symbolTable *tempNode;
    tempNode = (symbolTable*)malloc(sizeof(symbolTable));
    tempNode->kind = kind; //Run Time error Here..
    tempNode->type = type;
    tempNode->lexeme = identifier;
    tempNode->offSet = tempOffset;
    tempNode->nextTable = NULL;
    tempNode->nextSymbol = root;
    root = tempNode;
}

程序编译,然后当我尝试运行并插入到链接列表中时,我得到了这个错误:

Unhandled exception at 0x5A6810D0 (msvcr110d.dll) in mpcompiler.exe: 0xC0000005: Access   violation writing location 0xCDCDCDCD.

在指针中将字符串分配给另一个字符串的正确方法是什么?还是我做错了什么?任何帮助,将不胜感激!

谢谢!

【问题讨论】:

标签: c++ string pointers linked-list


【解决方案1】:

使用new 而不是malloc() 以便正确构造字符串对象:

tempNode = new symbolTable;

然后在以后需要释放节点时使用delete

delete node;

【讨论】:

    【解决方案2】:

    尝试将您的代码替换为

    void MPParser::insertToSymbolTable(string identifier, string type, string kind)
    {
        tempOffset++;
        symbolTable *tempNode;
        tempNode = new symbolTable;
        tempNode->kind = kind; //Run Time error Here..
        tempNode->type = type;
        tempNode->lexeme = identifier;
        tempNode->offSet = tempOffset;
        tempNode->nextTable = NULL;
        tempNode->nextSymbol = root;
        root = tempNode;
    }
    

    Access Violation 表示您正在写入未分配的内存。并且你绝不能在 C++ 中使用malloc,因为它不会调用constructors,始终使用new 来创建动态对象并使用delete 来释放它们。

    【讨论】:

      【解决方案3】:

      我在gcc 4.5.3下做了一个很简单的测试:

      #include <iostream>
      #include <string>
      
      struct A
      {
        std::string a;
      };
      
      int main()
      {
         A* ptr = new A;
         ptr->a = "hello";
         std::cout << ptr->a << std::endl;
      
         //A aStruct;
         A* ptr2 = (A*)malloc(sizeof(A));
         //ptr2 = &aStruct;
         ptr2->a = "hello again";   //simulate what you have done in your code
         std::cout << ptr2->a << std::endl;
         std::cin.get();
      };
      

      这将导致核心转储,因为ptr2 试图访问原始内存。但是,如果我取消注释:

      //A aStruct;
      //ptr2 = &aStruct;
      

      然后它按预期工作。因此,您应该使用new 而不是malloc。原因是new 会调用类的构造函数来初始化分配的内存块,而malloc 不会这样做。

      【讨论】:

        猜你喜欢
        • 2017-03-05
        • 2011-02-17
        • 1970-01-01
        • 1970-01-01
        • 2018-02-09
        • 2013-07-10
        • 2021-05-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多