1

Why is the following program stuck in a following loop after "Done!", and then ends with a crash?

#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);
}
Pwnna
  • 9,178
  • 21
  • 65
  • 91

5 Answers5

5

You do a lot of strcpy, but where are your mallocs?!

If you use C++ you should really use std::string to avoid things like this.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
4

Allocate memory for string before copying

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

Free the memory

delete[] beany.str;
cpx
  • 17,009
  • 20
  • 87
  • 142
1

A variety of problems:

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);
}

At the point of the call to strcpy, s.str is just a wild pointer. It doesn't point to anything valid.

This might be homework, but if not you should be using std::string instead of raw char*s. If you need to use raw char*s, then you need to allocate the space -- using new or, better yet, a smart pointer -- to which the pointers point. You can't just copy a string in to hyperspace and expect it to work.

John Dibling
  • 99,718
  • 31
  • 186
  • 324
1

I get a segmentation fault when I run your program. You need to allocate memory for s.str before the call to strcpy.

August Karlstrom
  • 10,773
  • 7
  • 38
  • 60
-1
 void set(stringy & s, const char * cs){
     s.ct = strlen(cs);
     strcpy(s.str, cs);
 }

s.str is unallocated. You need to do a

s.str = malloc(s.ct);
Tom Macdonald
  • 6,433
  • 7
  • 39
  • 59