首页 > 解决方案 > c++非法指令(核心转储)

问题描述

因此,我现在完成的程序按预期工作,除了当我按下“p”时发生的一次崩溃,它应该只将 if 语句切换到 else 部分,但是它会因“非法指令(核心转储)”消息而崩溃。

#include <stdio.h>
// include the UFCFGL301's standard library
#include <ufcfgl-30-1.h>
// uncomment if you want to use the graphics library
#include <graphics.h>


const uint32 window_Width = 600;
const uint32 window_Height = 400;

using namespace uwe;

struct Rect{
  int x,y,width,height,r,g,b;
};

struct Circle{
  int x,y,radius,r,g,b;
};

union CircleorRect{
  Rect rect;
Circle circle;
};

Rect createRect() {
  int x = rand() % window_Width;
  int y = rand() % window_Height;
  int width = rand() % 200;
  int height = rand() % 200;
  int r = rand()%256;
  int g = rand()%256;
  int b = rand()%256;
  return Rect{x, y, width, height, r, g, b};
};

Circle createCirc() {
  int x = rand() % window_Width;
  int y = rand() % window_Height;
  int radius = rand() % 200;
  int r = rand()%256;
  int g = rand()%256;
  int b = rand()%256;
  return Circle{x, y, radius, r, g, b};
};

Rect createRect();
Circle createCirc();

int main(void) {
// graphics window
initialiseGraphics(window_Width,window_Height);
// variables
int count = 0,pressedcount;
Circle circle[1000];
Rect rects[1000];
bool stopCircs = false;
// creating distinct shapes then mapping them.
loop(
  [&](){

    rects[count] = createRect();
    //if circles = create new circle and paint it
    if (stopCircs == false) {
      circle[count] = createCirc();
      for (size_t i = 0; i < count; i++) {
        setColour(circle[i].r,circle[i].g,circle[i].b);
        drawFilledCircle(circle[i].x,circle[i].y,circle[i].radius);
      }
    }
    else {
      for (size_t i = 0; i < pressedcount; i++) {
        setColour(circle[i].r,circle[i].g,circle[i].b);
        drawFilledCircle(circle[i].x,circle[i].y,circle[i].radius);
      }}

    for (size_t i = 0; i < count; i++) {
      setColour(rects[i].r,rects[i].g,rects[i].b);
      drawFilledRect(rects[i].x,rects[i].y,rects[i].width,rects[i].height);
    }

      count++;
      if (count >= 1000) {
        count = 0;
      }
  },
  [&](KeyPress keyPress){
    if (getTextCharacter(keyPress) == 'q') {
      return true;
    }
    else if (getTextCharacter(keyPress) == 'p') {
      stopCircs = true;
      pressedcount = count;
    }
    else {
      return false;
    }
  });
return 0;
}

'p' 按键应该只从生成新圈子切换到只加载旧圈子,不知道为什么会导致崩溃。这就是全部,所以如果有人想尝试运行它或告诉我如何获得比尝试失败更好的调试器,任何帮助将不胜感激。

标签: c++

解决方案


在这个 lambda 中,并非所有控制路径都有返回语句(使用更高的错误/警告级别编译可能会诊断出这种错误)。

[&](KeyPress keyPress){
    if (getTextCharacter(keyPress) == 'q') {
      return true;
    }
    else if (getTextCharacter(keyPress) == 'p') {
      stopCircs = true;
      pressedcount = count;
      //here maybe missing return
    }
    else {
      return false;
    }
// or here maybe missing return
}

推荐阅读