#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Location
    Georgia
    Posts
    20
    Rep Power
    0

    String size issues


    This is quite possibly a silly question (and I do hope it won't result in me being yelled at), but I've been out of C coding for a while so some of the tricks have faded although this SEEMED pretty straightforward.

    I'm sending a string through a socket using the following code:

    Code:
    //MAXBYTES has been defined as 32
    
            if( (sendbuffer = (char *)malloc(MAXBYTES)) == NULL){
                    printf("Error allocating memory for send buffer\n");
                    exit(1);
            }
    
    /*Socket and destination sock_addr struct creation */
                    sendbuffer="howdy";
                    printf("sendbuffer size: %d\n",sizeof(sendbuffer));
                    r_value = sendto(mySocket,sendbuffer,sizeof(sendbuffer),0,(struct sockaddr *)&dest_address,sizeof(dest_address));
    On runtime the printf prints "sendbuffer size: 4" every time and the receiver only gets "howd". I'm perplexed, anyone care to enlighten me?

    Thanks a bunch,

    Bill
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,091
    Rep Power
    2222
    sendbuffer is a char* pointing to the literal string "howdy". Or it could be viewed as the name of a char array, since array names and pointers are equivalent in C.

    So when you do a sizeof(sendbuffer), you are getting the size of a char pointer, which is 4. Instead, you want the length of the string, which you get with strlen(sendbuffer). BTW, this will not include the null-terminator, but I don't think you'd need to send that.

    Now, if instead you had explicitly declared a char array, then sizeof would have worked for you here. In a test program I just whipped up:
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    int main(void)
    {
        char s1[] = "howdy";
        char *s2 = "howdy";
    
        printf("Size of s1 = %d\n",sizeof(s1));
        printf("Size of s2 = %d\n",sizeof(s2));
    
        return 0;
    }
    The output was:
    C:\dcw\PROJECTS\TEST>a
    Size of s1 = 6
    Size of s2 = 4

    C:\dcw\PROJECTS\TEST>

    As you can see, sizeof on the array s1 returned the full size of the array, including the null-terminator.
    Last edited by dwise1_aol; July 7th, 2003 at 09:59 AM.

IMN logo majestic logo threadwatch logo seochat tools logo