0

私は現在、情報の文字列を含む文字列を持つリンクリストに取り組んでいます。次のような構造体を使用しています。

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.

ポインターで文字列を別の文字列に割り当てる正しい方法は何ですか? または、私は何か完全に間違っていますか?どんな助けでも大歓迎です!

ありがとう!

4

3 に答える 3

2

文字列オブジェクトが適切に構築されるように、new代わりに使用します。malloc()

tempNode = new symbolTable;

そして、delete後でノードを解放する必要があるときに使用します。

delete node;
于 2013-04-01T19:18:28.700 に答える
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割り当てられていないメモリに書き込んでいることを意味します。またmalloc、C++ では を呼び出さないため、絶対に使用しないでください。constructors常にnew動的オブジェクトを作成deleteして解放するために使用してください。

于 2013-04-01T19:19:21.453 に答える
1

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それは行われません。

于 2013-04-01T19:29:36.023 に答える