C ++程序崩溃

时间:2011-05-13 14:43:58

标签: c++

为什么以下程序在“完成!”之后卡在后续循环中,然后以崩溃结束?

#include <iostream>
using namespace std;
#include <cstring>

struct stringy{
    char * str;
    int ct;
};

void set(stringy & s, const char * cs);
void show(const char * s, int times=1);
void show(const stringy & s, int times=1);

int main(){
    stringy beany;
    char testing[] = "Reality isn't what it is used to be.";
    set(beany, testing);
    show(beany);
    show(beany, 2);
    testing[0] = 'D';
    testing[1] = 'u';

    show(testing);
    show(testing, 3);
    show("Done!");

    return 0;
}

void set(stringy & s, const char * cs){
    s.ct = strlen(cs);
    strcpy(s.str, cs);
}

void show(const char * s, int times){
    while (times-- > 0){
        cout << s << endl;
    }
}

void show(const stringy & s, int times){
    show(s.str, times);
}

5 个答案:

答案 0 :(得分:5)

你做了很多strcpy,但你的malloc s在哪里?!

如果你使用C ++,你应该真的使用std :: string来避免这样的事情。

答案 1 :(得分:4)

在复制之前为字符串分配内存

void set(stringy & s, const char * cs){
    s.ct = strlen(cs);
    s.str = new char[s.ct+1];
    strcpy(s.str, cs);
}

释放内存

delete[] beany.str;

答案 2 :(得分:1)

各种问题:

struct stringy{
    char * str;
    int ct;
};

// [snip]

stringy beany;
char testing[] = "Reality isn't what it is used to be.";
set(beany, testing);

void set(stringy & s, const char * cs){
    s.ct = strlen(cs);
    strcpy(s.str, cs);
}

在调用strcpy时,s.str只是一个狂野的指针。它没有指出任何有效的东西。

这可能是家庭作业,但如果不是,您应该使用std::string而不是原始char*。如果你需要使用原始char*,那么你需要分配空间 - 使用new,或者更好的是,指针指向的智能指针。你不能只是将一个字符串复制到超空间中并期望它能够工作。

答案 3 :(得分:1)

运行程序时出现分段错误。在调用strcpy之前,需要为s.str分配内存。

答案 4 :(得分:-1)

 void set(stringy & s, const char * cs){
     s.ct = strlen(cs);
     strcpy(s.str, cs);
 }

s.str未分配。你需要做一个

s.str = malloc(s.ct);
相关问题