Is there a problem with actually posting this short code sample using standard code tags instead of posting as an attachment?
Code:
#include"start.cpp"
char* _str(int,char); //(buffer size,terminating character)
int main(){
char *str;
str = _str(10,'$');
puts(str);
cout<<strlen(str);
getch();
return 0;
}
char* _str(int buffer,char tc){ //tc:- terminating character
int b=buffer;
char temp,*str,*rstr,*tstr;
int i,bt=b;
tstr=NULL;
rstr=NULL;
tstr=new char[b]; //no use of this.This is for line 45 to execute for 1st iteration of while.
rstr=new char[b]; //same as above but for line 48
while(1){
str=NULL;
str=new char[buffer];
for(i=0;i<buffer;i++){
temp=getche();
if(temp==tc){
cout<<endl;
str[i]='\0';
b=i;
break;
}
else if(temp==13){ //ascii value of ENTER key (lc i.e. line carriage)is 13
str[i]=10; //ascii value of newline (lf i.e. line feed) is 10
cout<<endl;
}
else{
str[i]=temp;
}
}
for(i=0;i<b;i++){
tstr[bt-buffer+i]=str[i]; //line 45
}
//delete [] rstr; //line 48
rstr=NULL;
char *rstr;
rstr=NULL;
rstr=new char[bt];
for(i=0;i<(bt-buffer+b);i++){
rstr[i]=tstr[i];
}
// delete [] tstr;
//tstr=NULL;
if(b!=buffer){
//delete [] str;
str=NULL;
rstr[bt-buffer+b]='\0';
return rstr;
}
char *tstr;
tstr=NULL;
tstr=new char[bt+buffer];
for(i=0;i<bt;i++){
tstr[i]=rstr[i];
}
bt = bt+buffer;
//delete [] str;
}
}
You should not be including source files with #include. Additional source files should instead be compiled/linked together as part of a project.
You are using non-standard I/O function calls (getche) and mixing this with C++ I/O (cout) which has already been mentioned is a no-no.
Your char array str has the potential of not being null-terminated within the allocated bounds.
You are redeclaring rstr and tstr within the loop and you allocate memory to both sets of these variables and reference different ones at different times within the loop.
You've commented out all you deallocation code so your hemorrhaging memory all over the place.
I'm stopping there, it's too painful to look at this code.