[C] strlen, strcat and malloc

From: Fatted (obeseted_at_yahoo.com)
Date: 07/29/04


Date: Thu, 29 Jul 2004 16:59:45 +0200

Consider code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 

int main(void)
{
         char *a;
         char b[] = "0123456789";
 

         if( (a = malloc(strlen(b) + 1) ) == NULL)
         {
                 perror("malloc!");
                 return(0);
         }
 

         strcat(a,b);
         printf("1:%s\n",a);
         strcat(a,b);
         printf("2:%s\n",a);
         free(a);
 

         return(0);
}

Results in:
1:0123456789
2:01234567890123456789

1) strlen returns the number of characters in b. Why don't I have to
multiply this value by sizeof(char) to allocate the correct amount of
memory to store char string b ( +1 for the \0 of course :)
2) For the second strcat, does strcat handle enlarging the amount of
memory defined for a, or did I just get lucky (I originally malloc'ed
enough for 1 char string b, but not 2)?



Relevant Pages