Click to See Complete Forum and Search --> : why do i need the extra byte ??


Zerg
October 17th, 1999, 10:49 PM
int A(char **temp) {
*temp = (char *)malloc(sizeof (char) * strlen("abcdefg")) ;
strcpy(*temp,"abcdefg") ;
return 0 ;
}
int main() {
char *temp ;
A(&temp) ;
free(temp) ; // kaboom !!
return 0 ;
}

the solution is, in function A, i shld do this
*temp = (char *)malloc(sizeof (char) * strlen("abcdefg")+1) ;
my question is, why sizeof strlen("abcdefg") is not enough ?
what is use of the extra byte ?
thanks alot.

Signature (up to 100 characters) You may use Markup in your signature

Todd Jeffreys
October 17th, 1999, 11:55 PM
Strings in C/C++ are NULL-Terminated. Meaning that if you have a char *string="test"; you would have a memory block of size 5, havning 't' 'e' 's' 't' '\0'. The \0 indicates the end of the string. Therefore, when you do string operations you must always leave space for the string terminator