为什么程序S_object.findShortestWord(S_object.get(), str_value2);以终止Process returned -1073741819 (0xC0000005) execution time : 3.804 s?
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
class FirstClass {
public:
char* str_value;
public:
FirstClass(const char* value = ""):str_value(0) {
set(value);
}
FirstClass(const FirstClass &obj):str_value(0) {
set(obj.str_value);
};
~FirstClass() {delete[] str_value;}
void set(const char* value) {
delete[] str_value;
str_value = new char[strlen(value)+1];
strcpy(str_value, value);
}
const char* get() const {
return str_value;
}
};
class SecondClass : public FirstClass {
public:
SecondClass(const char* str_value = "") : FirstClass (str_value) {}
void findShortestWord(const char* in, char* out) {
int len = strlen(in);
int beginWord = 0;
int lengthWord = 0;
for (int i = 0; i < len; i++) {
while ( (in[i] == ' ') && ( in[i] != '\0') ) i++;
int begin = i;
while ( (in[i] != ' ') && (in[i] != '\0') ) i++;
int end = i;
char tmp[256];
for(int j = begin, k=0; j < end; j++, k++)
tmp[k] = in[j];
tmp[end - begin] = '\0';
int currentLen = end - begin;
if (currentLen < lengthWord) {
lengthWord = currentLen;
beginWord = begin;
}
}
for (int i = beginWord, k = 0; i < beginWord + lengthWord; i++, k++)
out[k] = in[i];
out[lengthWord] = '\0';
}
};
int main() {
char* str_value2;
FirstClass F_object("Hello my world 1");
printf("\nFirstClass init: %s", F_object.get());
F_object.set("Hello my world 2");
printf("\nFirstClass set: %s", F_object.get());
FirstClass F_object2 = F_object;
SecondClass S_object(F_object.get());
printf("\nSecondClass init: %s", S_object.get());
S_object.findShortestWord(S_object.get(), str_value2);
//F_object = S_object;
printf("\nSearch and delete: %s", str_value2);
return 0;
}
str_value2例如需要分配内存char str_value2[256]。或char* str_value2 = new char[256]。编译器立即发誓——使用了一个未初始化的变量
str_value2!那些。你写在某个“某处”有一个完全随机地址的地方……程序崩溃有什么奇怪的吗?