0

I'm running into an irritating problem where my program keeps crashing if I try to reference a private variable that I have created in one of my classes. I can't figure out where I am going wrong. Here is the class that calls the class that crashes:

#include <stack>
#include <fstream>
#include <ostream>
#include <cstdlib>
#include <string>
#include <set>
#include "schemeList.cpp"

using namespace std;

class dataLog
{
public:
stack<string> commands;
set<string> domain;
processor tokens;
int nextToken;
schemeList * s;
dataLog(stack<string> s, ofstream * out, processor p, int location)
{
    commands = s;
    tokens = p;
    nextToken = location;
    commands.push("<Query List>");
    commands.push(":");
    commands.push("Queries");
    commands.push("<Rule List>");
    commands.push(":");
    commands.push("Rules");
    commands.push("<Fact List>");
    commands.push(":");
    commands.push("Facts");
    commands.push("<Scheme List>");
    commands.push(":");
    commands.push("Schemes");
    checkNext();
}

void checkNext()
{
    for(int i = 0; i < tokens.tags.size(); i++)
    {
        if(commands.top().compare(tokens.tags[i].getName())!=0)
        {
            if(commands.top().find("<")==0)
            {
                if(commands.top().compare("<Scheme List>")==0)
                {
                    int output = (*s).process(i, tokens, domain);                       string hi = (*s).toString();

                }
            }
        }
        commands.pop();
    }

}
};

This class creates an object of my SchemeList class, which is written out as follows:

#include "schemes.cpp"
#include <cstdlib>
#include <string>
#include <set>
using namespace std;

class schemeList
{
private:
string success;

public:
int process(int number, processor p, set<string> domain)
{
    success = "HELLO";
    return 13;
}

string toString()
{
    return success;
}

};

As soon as I get to line 15 success = "HELLO";, the program crashes with the message

Unhandled exception at 0x00E48B66 in lab2.exe: 0xC0000005: Access violation reading   
 location 0xCCCCCCE4.

I am using Microsoft Visual Studio Express 2012 for Windows Desktop.

4

3 回答 3

3

首先,变量schemeList * dataLog::s从未初始化,因此访问它是未定义的行为,这会导致崩溃。最有可能在悬空指针上调用进程并尝试写入您不拥有的一些内存。

第二,不要#include "schemeList.cpp"。您不应该包含cpp文件。相反,将声明和实现分开并包含标题。

于 2012-09-24T08:11:29.737 回答
1

你还没有初始化dataLog::s。当你打电话时(*s).process(i, tokens, domain),你会得到未定义的行为。

于 2012-09-24T08:15:45.983 回答
0

首先,您显然在标头中包含源代码文件。这可能会打破单一定义规则并出现可怕的错误。

其次,“s”对于班级成员来说不是一个很好的名字。这使得几乎不可能找到它的用途。

第三,我在您的初始化 s 的代码中看不到任何地方。我可以看到它在哪里被引用了,但是由于它还没有被初始化,取消引用的效果是未定义的,幸运的是只会让你的程序崩溃,这看起来就像正在发生的事情。

于 2012-09-24T08:16:11.910 回答