Need help concatentating 2 strings and an int.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dissectcode2
    New Member
    • Apr 2009
    • 32

    Need help concatentating 2 strings and an int.

    Hi - please help. I have two strings and a number which I need to concatenate together and I'm confused to what is the best approach. Here is my code:

    Code:
    char *s1 = "iamafilename_";
    char *s2 = ".tif";
    
    int i;
    for( i = 0; i < 10; i++ )
    {
    
     char itoaBuff[100];
     int num_len = sprintf(itoaBuff, "%s", i);
    
     char *f = (char *)malloc( (strlen(s1) + strlen(s2) + num_len) * sizeof(char) + 1 );
    
     strcat( f, s1 );
     strcat( f, itoaBuff );
     strcat( f, s2 );
    
     printf("the three strings concatenated is: %s\n\n", f);
    
     free( f );
           
    }


    i get a seg fault by the way. can anyone see what i am trying to do and advise me please?
  • dissectcode2
    New Member
    • Apr 2009
    • 32

    #2
    I wish I could delete this post because I realized my sprintf needed %d inside and it worked. I'm smarter than I thought. pat pat

    Comment

    • dissectcode2
      New Member
      • Apr 2009
      • 32

      #3
      or would it have been better to use scanf ??

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        What I notice is:

        Code:
        strcat( f, s1 ); 
         strcat( f, itoaBuff ); 
         strcat( f, s2 );
        strcat operates by appending after a \0 which your buffer f may not have. I suggest an initial strcpy then the strcats:

        Code:
        strcpy( f, s1 ); 
         strcat( f, itoaBuff ); 
         strcat( f, s2 );
        or at least set f[0] to \0 before the strcats.

        Without that initial \0 your strcat will append an indeterminate number of bytes. That could cause you to overrun f and corrupt memory.

        Comment

        • dissectcode2
          New Member
          • Apr 2009
          • 32

          #5
          thank you weaknessforcats because i was going crazy with a seg fault, and thought it might have something to do with all strcat's, and you validated it with good info. now i know what is the correct approach.

          Comment

          Working...