简体   繁体   English

C ++程式当机

[英]C++ program crashes down

I'm doing a project with C++ and my program keeps crashing down when I try to run it...here is my code (two files: main.cpp and PlacementHead.cpp ): 我正在用C ++做一个项目,当我尝试运行它时,程序不断崩溃……这是我的代码(两个文件: main.cppPlacementHead.cpp ):

main.cpp: main.cpp中:

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <climits>
#include "PlacementHead.h"

// Main

int main (int argc, char * const argv[]) {

        PlacementHead h1(4,2,1,"aabcbbca");
        PlacementHead h2(4,2,1,"babcabca");

    return 0;
}

PlacementHead.cpp: PlacementHead.cpp:

#include "PlacementHead.h"
#include <string>
#include <iostream>
#include <string.h>

PlacementHead::PlacementHead(int width, int height, int gap, char* s) {
    width_ = width;
    height_ = height;
    gap_ = gap;
    size_ = width*height;
    set_ = new char[size_];
    from_ = new int[size_];
    original_ = new char[size_];
    strcpy(set_,s);
    strcpy(original_,s);
}

PlacementHead::~PlacementHead() {

}

int PlacementHead::getSize() { return size_; }
int PlacementHead::getHeight() { return height_; }
int PlacementHead::getWidth() { return width_; }
int PlacementHead::getGap() { return gap_; }

char PlacementHead::getNozzle(int i) {
    return set_[i-1];
}

void PlacementHead::setNozzle(int i, char c) {
    set_[i-1] = c;
}

void PlacementHead::markNozzle(int i, int bankPos) {
    set_[i-1] = ' ';
    from_[i-1] = bankPos;
}

int PlacementHead::getNextUnmarkedPos() {
    for (int i=0; i<size_; i++) {
        if (set_[i]!=' ') {
            return i+1;
        }
    }
    return 0;
}

int PlacementHead::getBankPos(int i) {
    return from_[i-1];
}

void PlacementHead::reset() {
    //for (int i=0; i<size_; i++) {
    //  set_[i] = original_[i];
    //}
    strcpy(set_,original_);
}

void PlacementHead::print() {
    std::cout << "placementhead:\n";
    for (int h=height_; h>0; h--) {
        for (int w=width_; w>0; w--) {
            int i = ((h-1)*width_)+w;
            std::cout << getNozzle(i);
        }
        std::cout << "\n";
    }
}

If I try to run the main.cpp, I get this: 如果我尝试运行main.cpp,则会得到以下信息:

在此处输入图片说明

Once I got this also (I don't get this every time, which bugs me...): 一旦我也得到了这个(我不是每次都得到这个,这让我很烦...):

在此处输入图片说明

Now here is also one thing to take into account: If I comment out the second line where PlacementHead h2-object is created the code runs okay, but IF I create more than one PlacementHead-objects the program crashes again... 现在这也是要考虑的一件事:如果我注释掉创建PlacementHead h2-object的第二行,代码可以正常运行,但是如果我创建多个PlacementHead-objects,程序将再次崩溃...

Any advices what might be causing this? 任何建议可能是什么原因造成的? Thank you for any help!! 感谢您的任何帮助!! =) =)

PS PS

My platform is Windows 7, Codeblocks 12.11 and GNU GCC Compiler 我的平台是Windows 7,Codeblocks 12.11和GNU GCC编译器

UPDATE: 更新:

In case you couldn't see the text on the second picture here it is: 如果您看不到第二张图片上的文字,则为:

在此处输入图片说明

size_ = width*height; should be size_ = (width*height)+1; 应该是size_ = (width*height)+1; so the string can be null terminated. 因此该字符串可以以null结尾。 Currently you are writing to unallocated memory causing undefined behaviour 当前,您正在写入未分配的内存,导致未定义的行为

You should 你应该

  • increase size_ by +1 too avoid buffer overrun (or, use std::vector instead, see below) size_增加+1也要避免缓冲区溢出(或者使用std::vector代替,请参见下文)
  • disable copy construction/assignment 禁用副本构建/分配
  • add a proper destructor 添加适当的析构函数
  • use initialization lists 使用初始化列表
  • check the order in which members are declared (since this is also the order in which members are initialized !) 检查成员的声明顺序(因为这也是成员初始化的顺序!)
  • remove the default constructor, since it doesn't initialize a single member 删除默认构造函数,因为它不会初始化单个成员
  • include <cstring> instead of <string.h> on modern compilers (so you get namespaces C standard library functions) 在现代编译器中包含<cstring>而不是<string.h> (因此您可以获得名称空间C标准库函数)

Consider using std::vector instead of manual arrays. 考虑使用std::vector代替手动数组。 This will save you much trouble. 这将为您节省很多麻烦。 Think of how you are going to get your constructor exception safe? 想一想如何使构造函数异常安全?

Here is a sample fixing all of the above: 这是修复以上所有问题的示例:

#include <iostream>
#include <vector>
#include <cstring>

struct PlacementHead {
    int width_, height_, gap_;
    size_t size_;

    std::vector<char> set_, original_;
    std::vector<int> from_;

    PlacementHead(int width, int height, int gap, const char* s) :
        width_(width),
        height_(height),
        gap_(gap),
        size_(width * height),
        set_(s, s + std::min(strlen(s), size_)),
        original_(set_),
        from_(size_)
    {
        set_.resize(size_);
        original_.resize(size_);

    }

    size_t getSize() { return size_; }
    int getHeight() { return height_; }
    int getWidth() { return width_; }
    int getGap() { return gap_; }

    char getNozzle(int i) { return set_[i - 1]; }

    void setNozzle(int i, char c) { set_[i - 1] = c; }

    void markNozzle(int i, int bankPos) {
        set_[i - 1] = ' ';
        from_[i - 1] = bankPos;
    }

    int getNextUnmarkedPos() {
        for(unsigned i = 0; i < size_; i++) {
            if(set_[i] != ' ') {
                return i + 1;
            }
        }
        return 0;
    }

    int getBankPos(int i) { return from_[i - 1]; }

    void reset() {
        //for (int i=0; i<size_; i++) {
        //  set_[i] = original_[i];
        //}
        set_ = original_;
    }

    void print() {
        std::cout << "placementhead:\n";
        for(int h = height_; h > 0; h--) {
            for(int w = width_; w > 0; w--) {
                int i = ((h - 1) * width_) + w;
                std::cout << getNozzle(i);
            }
            std::cout << "\n";
        }
    }
};

// Main

int main (int argc, char * const argv[]) {

    PlacementHead h1(4,2,1,"aabcbbca");
    PlacementHead h2(4,2,1,"babcabca");

    return 0;
}

You have an off-by-one error in your constructor, as the strings you try to copy are not 8 characters, they are 9. The reason is that all string literals are also containing an extra special string termination character. 您的构造函数中存在一个错误的错误,因为您尝试复制的字符串不是 8个字符,而是9个。原因是所有字符串文字都还包含一个额外的特殊字符串终止字符。

If you're using strings in C++, use std::string , it will help you tremendously with problems like these. 如果您在C ++中使用字符串,请使用std::string ,它将极大地帮助您解决此类问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM