Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why does this code allocate too much space?

Status
Not open for further replies.

strack

Programmer
Jan 27, 2001
3
0
0
US
I have just begun learning pointer operations, and am attempting to create a function that will reverse a string. For some reason, however, revString is always allocated with an extra 4-5 bytes. The code is below, and I would appreciate anyone's help.

Code:
char *strrev(char *string)
{
	int n=strlen(string);
	char* revString=new char[n];

	while( n-- )
		*(revString+n) = *(string++);
	
	return revString;
}
 
You should add
revString[n]='\0';
to terminate your string before you reverse it.
 
And moreover, you should allocate one more byte for the null terminator.
 
I will make an assumption here and say it is a padding issue. Just for kicks try to rever the string "ABCD" and see if it works correctly. Also, I would do the new with n+1 and not n so you could add an extra character at the end of '\0' or 0 (zero). This may be your problem as well.

Matt
 
Bad things can be with n = 0: new char[0] does not work (that is one of reasons to work witn n+1 (see Jeffray and Zyrenthian). Do it so:
char *strrev(char *string)
{
if(string == 0)
return (char*)NULL; //if string == NULL, strlen does not work
int n=strlen(string); //strlen returns size_t, not int -> by very-very big strings n < 0
char* revString=new char[n+1];

if(revString == NULL)
return (char*)NULL; //Not enough memory; for example, string hasn't 0 on end

revString[n] = 0; //or revString[n]='\0'; - it works by n= 0 too

while( n-- )
*(revString+n) = *(string++);

return revString;
}
 
Thanks for your help. It was a null terminator problem.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top