why do i need the extra byte ??
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
Re: why do i need the extra byte ??
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