CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8
  1. #1
    Join Date
    Oct 2006
    Posts
    7

    strlen vs sizeof

    Code:
    #include <stdio.h>
    #include<string.h>
    
    main()
    {
    	char string[] = "october";
            strcpy(string, "september");
    	
    	printf("the size of %s is %d and the length is %d\n\n", string, sizeof(string), strlen(string));
    	
    	return 0;
    }
    right. the size should be the length plus 1 yes?

    this is the output
    Quote Originally Posted by command prompt
    the size of september is 8 and the length is 9

    Press any key to continue
    size should be 10 surely. its like its calculating the sizeof string before it is changed by strcpy but the length after.

    Is there something wrong with my syntax or what?

    thanks

  2. #2
    Join Date
    May 2002
    Posts
    1,435

    Re: strlen vs sizeof

    sizeof() returns the size of the operand, not a string length - they are two different things. When you declared 'string[]' it's size was fixed at 8 no matter what you copy into it later. In fact, you are overwriting the bounds of 'string' by copying another string that required 10 bytes. That's a good way to guarantee a program execution error.

  3. #3
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    Re: strlen vs sizeof

    It's anyways bad practice to initialie a char array with a string literal. So always do one of the following:
    Code:
    const char string1[] = "october";
    char string2[20]; strcpy(string2, "september");
    More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf

    Premature optimization is the root of all evil --Donald E. Knuth


    Please read Information on posting before posting, especially the info on using [code] tags.

  4. #4
    Join Date
    Sep 2004
    Location
    Holland (land of the dope)
    Posts
    4,123

    Re: strlen vs sizeof

    It's anyways bad practice to initialie a char array with a string literal.
    Why ?

  5. #5
    Join Date
    Nov 2006
    Posts
    1,611

    Re: strlen vs sizeof

    I'm not ignoring you Skizmo, just leaving THAT debate for you.

    I wanted to point out that sizeof shouldn't be used with character arrays unless you're managing memory. There is no good relationship between sizeof and strlen when dealing with what most of us think of as strings.

    These are C style snippets, and perhaps everyone things of character arrays as strings (the terms were once used interchangeably), but in C++ we take greater care to distinguish what we're REALLY thinking, both in terms of types and concepts.

    The concept here is a string, but the type is a character array.

    A string is a larger notion, and may require you to move into unicode, MCBS or who knows what. In unicode, the underlying character type (and there's another double meaning - character as in one character in a word, not a char data type) might be a 16 bit unsigned short, in which case the relationship between sizeof and strlen are way off.

    MCBS is worse, because conceptually several characters in the string have different lengths (though most of us don't witness this), in which case there can be an insane lack of relationship between sizeof and strlen.

    You really don't want to mix the two concepts.

    I understand that here you ARE indeed comparing the memory layout question against the string content question - where sizeof, strlen, allocated space and zero termination all come into play - but just a few days ago I responded to a post where someone was using sizeof as a substitute for strlen and getting into trouble.

    All of these issues (and much more) are why string classes are important.
    If my post was interesting or helpful, perhaps you would consider clicking the 'rate this post' to let me know (middle icon of the group in the upper right of the post).

  6. #6
    Join Date
    Oct 2006
    Posts
    7

    Re: strlen vs sizeof

    thanks guys. i understand now, apart from the last post.

  7. #7
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: strlen vs sizeof

    The last post essentially says "Never use sizeof to determine the actual length of a string, and never use strlen to determine how much space is available for a string."

    It also implies that if you ever have sizeof(string) <= strlen(string), you're in trouble because you're corrupting other memory somewhere.

  8. #8
    Join Date
    May 2000
    Location
    Washington DC, USA
    Posts
    715

    Re: strlen vs sizeof

    Let me try to simplify this.

    sizeof() is an operator used to determine the size of a variable. ( will never blow up ).
    strlen() is a function which counts the number of bytes in a string before the terminator '\0' character. ( will very likely blow up if your string is not null terminated. )

    thus
    Code:
    char szString[10] = "yada";            // 4 bytes + 1 terminator, in a 10 byte array
    char szZapo []     = "badabing";     // 8 bytes + 1 terminator in 9 byte array ( 8+1)
    
    printf( "sizeof( szString ) = %d\n", sizeof( szString ));  // 10 size of array
    printf( "sizeof( *szString) = %d\n", sizeof( *szString )); // 1 cause first element 'y' is a byte
    
    printf( "strlen(szString) = %d\n", strlen(szString)); // 4  number of chars before terminator
    
    printf( "sizeof( szZapo ) = %d\n", sizeof( szZapo ));  // 9 size allocated for array including terminator
    printf( "sizeof( *szZapo) = %d\n", sizeof( *szZapo )); // 1 cause first element 'b' is a byte
    
    printf( "strlen(szZapo) = %d\n", strlen(szZapo)); // 8  number of chars before terminator

    Also don't try to use sizeof(buff) > strlen(buff) to test to see if you are corrupting memory. Cause if you've corrupted memory you are hosed before this boolean test statement is true.
    Last edited by JMS; November 13th, 2007 at 02:58 PM.

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