CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 1999
    Location
    Pacific Ocean, Deep Blue Sea
    Posts
    133

    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

  2. #2
    Join Date
    Apr 1999
    Posts
    396

    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
  •  





Click Here to Expand Forum to Full Width

Featured