|
-
October 17th, 1999, 10:49 PM
#1
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
-
October 17th, 1999, 11:55 PM
#2
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|