我的C ++代码遇到了问题,这些代码已成功编译,但在执行时会出现分段错误。麻烦的一点是,我无法真正解决这个问题,我不明白为什么我不能使用gdb来缩小它。
我正在编写教程OpenGL 4代码。一开始我尝试根据实际屏幕尺寸创建逻辑地图。编写LogicController类是为了将OpenGL(和glfw)给出的实际内容传递给algorythms,反之亦然。
这是代码。
int main(int argc, char const *argv[]) {
<...>
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
<...>
LogicController logicController( objects_num, mode->width, mode->height, model_area_percentage, move_speed );
<...>
}
,用户提供的objects_num
为int
,model_area_percentage
和move_speed
是硬编码的const float
。
LogicController构造函数使用传递给它的参数来构造一个Map
对象,这是一个逻辑映射:
LogicController::LogicController ( const int _objects_num, const int screen_width, const int screen_height, const float model_area_percentage, const float _move_speed ) :
objects_num ( _objects_num ),
move_speed ( _move_speed )
{
float square_area = ((screen_width * screen_height) / 100.0 ) * model_area_percentage;
float square_side = sqrt(square_area);
square_sizes = new Size( square_side/screen_width, square_side/screen_height );
width_in_squares = screen_width / square_side - 1;
height_in_squares = screen_height / square_side - 1;
std::cout << "Width in squares: " << width_in_squares << " Height in squares: " << height_in_squares << std::endl;
Map* map = new Map( width_in_squares, height_in_squares, objects_num - 1, 0 );
std::cout << "Map is successfully constructed";
setup_objects( objects_num, map );
}
问题从这里开始:正方形中有一个&#34;宽度&#34;在输出流中但是&#34; Map已成功构建&#34;执行时永远不会达到。崩溃发生在它之前。
这里是Map
构造函数:
Map::Map( const int _width, const int _height, const int _enemies_num, const int _obstacles_num ):
width( _width ),
height( _height ),
player_coordinates( 0, _width, 0, _height ),
enemies_num( _enemies_num ),
obstacles_num( _obstacles_num )
{
std::cout << "The very beginning of Map" << std::endl;
map = new int*[height];
for( int i = 0; i < height; i++ )
{
map[i] = new int[width];
for( int j = 0; j < width; j++ )
map[i][j] = 0;
}
populate_map( enemies_num, obstacles_num );
print_map( std::cout );
std::cout << "The very end of Map contructor" << std::endl;
}
void Map::print_map( std::ostream& out_stream )
{
for( int i = 0; i < height; i++ )
{
for( int j = 0; j < width; j++ )
out_stream << map[i][j] << " ";
out_stream << std::endl;
}
}
这些代码按照必须打印的方式打印地图,&#34; Map构造函数的最后一部分&#34;也是std::cout
- 编辑。
然后,据我所知,执行必须在std::cout
对象创建后返回map
,但它不会发生分段错误。因此,对象不是出于某种原因而创建的。我是否以某种方式弄乱指针?
以下是我编译代码的方法:
g++ main.cpp Map.cpp LogicController.cpp utilities.cpp game_objects.cpp ShadersHandler.cpp -o main -lGL -lglfw -lGLEW -std=c++11 -ggdb -Wall -Wextra -pedantic
编译时没有提示任何内容。所以更让我感到困惑的是:当我尝试使用gdb并运行代码时,即使设置了断点,它仍然是[Inferior 1 (process 733) exited with code 0377]
。我是否错误地使用它?
很抱歉有大型代码段,但我甚至不确定这里需要分析哪些代码段。我会很感激任何提示。
答案 0 :(得分:1)
关于gdb - 通过命令行使用它。语法是:
gdb {EXECUTABLE} {CORE_FILE}
然后,gdb将加载核心文件。之后,如果您的程序是单线程的,请插入bt
(bt = back-trace,我猜),您将看到您的进程的最后时刻......
如果您的程序是多线程的,请插入thread apply all bt
以查看所有程序。
要退出gdb,请使用q
。