Thread: strlen does not equal string length

  1. #1
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300

    strlen does not equal string length

    Under what conditions could this code:

    Code:
    filelen=strlen(word+1);
    file=malloc(filelen);
    strcpy(file,word);		
    printf("filelen: %d, %s\n", filelen,file);
    produce this output:

    Example 1: filelen: 7, cynosure
    Example 2: filelen: 4, twalk

    "file" is a char pointer, "filelen" is a short int.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  2. #2
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Code:
    filelen=strlen(word+1);
    For word not being an empty string longer than one, this is the same as:
    Code:
    filelen=strlen(word)-1;
    You are incrementing the char pointer, when you probably want to increment the result of strlen().
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by King Mir View Post
    Code:
    filelen=strlen(word+1);
    For word not being an empty string longer than one, this is the same as:
    Code:
    filelen=strlen(word)-1;
    You are incrementing the char pointer, when you probably want to increment the result of strlen().
    Exactly right.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strange string behavior
    By jcafaro10 in forum C Programming
    Replies: 2
    Last Post: 04-07-2009, 07:38 PM
  2. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  4. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  5. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM