struct FF{
void append( char *str ){
const int strLength = strlen( str );
const int totalLength = strLength + size;
char *tmp;
if( freeSpace < strLength ){
//not enough free space available for the str to append
//allocate the total str length including the current size + free space
tmp = new char[totalLength + 10];
freeSpace = 10;
//cpy old string and new string to tmp
for( int i = 0; i < size; i++ ){
tmp[i] = strVal[i];
}
for( int i = size; i < totalLength; i++ ){
tmp[i] = str[i];
}
delete[] strVal;
strVal = new char[totalLength+10];
size = totalLength;
strcpy( tmp, strVal );
}else{
for( int i = size; i <= totalLength; i++ ){
strVal[i] = str[i];
}
freeSpace -= strLength;
size += strLength;
}
}
char *strVal;
unsigned int size;
unsigned int freeSpace;
};
int main(){
FF a;
a.strVal = new char[10];
a.freeSpace = 10;
a.size = 0;
a.append( "str" ); // should have 7 bytes left
a.append( "len" ); // should have 4 bytes left
std::cout << a.strVal << std::endl; //prints str instead of strlen
return 0;
}
我希望strVal
拥有可用空间,这样每次我添加内容时都不必分配空间。但是,第一个附件工作正常。但是当我再次追加它时,它不起作用。所以最后只打印出str。
答案 0 :(得分:2)
问题是,else子句必须改为:
...
}else{
for( int i = 0; i <= strLength; i++ ){
strVal[i+size] = str[i];
}
freeSpace -= strLength;
size += strLength;
}
答案 1 :(得分:1)
你在第二个for循环中遇到问题:
...
for( int i = size; i < totalLength; i++ ){
tmp[i] = str[i];
}
i
可以使用tmp
,但str
不可以:<
...
for( int i = size; i < totalLength; i++ ){
tmp[i] = str[i<b> - size</b>];
}
之后,您无需为strVal
分配新缓冲区并从tmp
复制(再次):只需将tmp
分配给strVal
。
那就是摆脱strcpy(),其中参数的顺序是错误的,如@doctorlove所示。
最后,你有一个内存泄漏:为tmp
分配一个char数组,但从不释放它。如果您按上述方法更改处理方式,那么您也可以摆脱它。