I'm doing a C++ project for a PCB assembly thesis and I have been given (by my professor) an old set of C++ code. When I try test and run the code it chrashes...the program compiles ok, but it chrashes at runtime..here is the code:

2 Answers
2

The C library strcpy() requires a NUL terminated C style string. You have a char[] array that does not have a NUL terminator.

If you want to convert your randomized array of letters into a C-style string, you need to add one more element to the end, and set it to the value 0. Alternately, you need to turn your strcpy() calls into memcpy() calls and supply the length directly.

And then change all of your new char[size_] calls to new char[size_ + 1].

The cleaner approach would be to say what you mean, and treat this as an array of char, not a C string. Convert all your strcpy calls to memcpy. For example, this:

strcpy(set_,s);
strcpy(original_,s);

becomes this:

memcpy(set_,s,size_);
memcpy(original_,s,size_);

Note: Be sure to change allstrcpy to memcpy on these arrays. I think there is at least one other. I did not check your code that closely.

The latter is the better approach, IMHO, but I offer both.

Also, the above code leaks memory. That may not be a concern if it just runs through once and quits. You new [] memory that you never delete []. If your program is going to grow and have multiple instances of these objects coming and going, you'll want to add those delete[] calls, otherwise you're setting yourself up for a future crash of a different sort.

strcpy works by reading an array of characters until it reaches a null terminating character '\0' - However your source array does not contain a null terminating character. so strcpy will keep copying forever, reading memory it doesn't have access to, and writing past the end of your destination array, either of which could cause the crash. You need to either use strncpy (which you should always prefer), which only copies a fixed number of characters.

You should in general always leave an extra space in any character array if you intend on treating the characters as a string, like strcpy does. If you are only using individual elements and treating the individual characters on their own, then you don't need to. You could equally use memcpy in that case.

There may be other problems in the code, this is just one I have spotted.

You also have memory leaks, you should delete[] the member variables you new[]