2014-03-05 74 views
6

我想从C++,Visual Studio 2010中的外部库中定义一个变量。它只在我把它放在主函数之外时才起作用。C++ - 在main()函数内部定义变量时遇到问题

该代码崩溃:

#include "StdAfx.h" 
#include <ogdf\basic\Graph.h> 
#include <ogdf\basic\graph_generators.h> 

int main() 
{ 
    ogdf::Graph g; 
    ogdf::randomSimpleGraph(g, 10, 20); 
    return 0; 
} 

它给了我一个unhandheld异常:访问冲突。 但是,如果是外面的主要功能,它的工作没有任何问题:

#include "StdAfx.h" 
#include <ogdf\basic\Graph.h> 
#include <ogdf\basic\graph_generators.h> 

ogdf::Graph g; 

int main() 
{ 
    ogdf::randomSimpleGraph(g, 10, 20); 
    return 0; 
} 

你有什么我怎么解决这个问题?我认为,这是由某种链接问题引起的。

编辑:它看起来像问题不是变量的初始化。它在应用程序退出时引发异常。

int main() 
{ 
ogdf::Graph g; // No problem 
ogdf::randomSimpleGraph(g, 10, 20); // No problem 
int i; // No problem 
std::cin>>i; // No problem 
return 0; // Throws an exception after read i; 

}

调用堆栈:Call STack

输出是:在graphs.exe在0x0126788f 第一次机会异常:0000005:访问冲突写入位置00000000。

graphs.exe中的0x0126788f未处理的异常:0xC0000005:访问冲突写入位置0x00000000。

+4

它可能与全局变量是零初始化有关,而局部变量具有不确定的值。如果在本地声明时显式地初始化'g'会怎么样? –

+2

@JoachimPileborg:但ogdf ::图是一个类,构造函数希望做初始化的东西。文档是[here](http://www.ogdf.net/doc-ogdf/classogdf_1_1_graph.html) –

+1

你还可以发布堆栈转储吗?这将是有趣的**哪里**例外被提出,并且因为哪个地址。 – Flovdis

回答

5

适用于我的机器™。

像这样的密教错误往往是二元不兼容的结果。基本上,由于不同的编译器/预处理器选项,您的代码和库“看到”的有效标题是不同的。

举例来说,如果你有下面的头代码库:

class Foo 
{ 
#ifdef FOO_DEBUG 
    int debug_variable; 
#endif 
    int variable; 
}; 

库函数:

void bar(Foo& foo) 
{ 
    std::cout << foo.variable; 
} 

和客户端代码:

Foo foo; 
foo.variable = 666; 
bar(foo); 

如果FOO_DEBUG不客户端和库中的同步,这可能会崩溃并烧伤 - variable将有不同的预期偏移量。

在你的情况,我怀疑下列情况之一可能为真:

  • 你已经建立了不同的编译器ogdf比你的代码
  • 如果没有,你ogdf和你的代码有不同的生成配置(发布版vs调试)
  • 两者都调试,但您已经定义OGDF_DEBUG(推荐here
  • 你有不同的“结构成员对齐方式”设置