【发布时间】:2016-12-05 17:30:14
【问题描述】:
这可能是一个愚蠢的问题,但是为什么调用删除时这段代码会崩溃?通过阅读其他问题,我知道这可能会导致未定义的行为,但我不明白为什么。
#include <iostream>
using namespace std;
char* resize (char* result, int& size){
char * temp;
temp = new char [size*10];
for (int i=0;i<size;i++) temp[i]=result[i];
size*=10;
//delete[] result;
return temp;
}
void transform(char in[], const char p1[], const char p2[]){
int resultlength=100, inputindex=0, outputindex=0;
char* result = new char[resultlength];
while (in[inputindex]){
result[outputindex++]=in[inputindex++];
if (inputindex>=resultlength) result = resize (result,resultlength);
}
in[outputindex--]=0;
while(outputindex>=0) in[outputindex]=result[outputindex--];
//delete[] result;
}
int main(){
char t[200]="123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345";
transform(t,"hfgh","dfsdfds");
int i=0;
while(t[i]) cout<<t[i++];
cout<<endl;
return 0;
}
【问题讨论】:
-
result = temp对函数的调用者没有任何意义。通过引用传递该指针,或者可能利用函数的其他未使用的返回值。这个问题有 数百个 重复项,但标题、描述和内容大相径庭,很难确定一个。 -
我已经改变,所以它传递一个指针的引用,它仍然在到达删除时崩溃。
-
我现在感觉很愚蠢,但是是的,错字是个问题(除了另一个错误)。谢谢。