1,105,578 Community Members

strlen of strdup

Member Avatar
Junior Poster
160 posts since Aug 2008
Reputation Points: 39 [?]
Q&As Helped to Solve: 9 [?]
Skill Endorsements: 0 [?]


  1. Question
    Why does valgrind complain?
    Conditional jump or move depends on uninitialised value(s)
    ==25636==    at 0x4C26D29: strlen (mc_replace_strmem.c:242)
    ==25636==    by 0x40060A: main (test.c:7)
  2. Question
    Strlen doesnt apparantly tell you how much space you have in your array, but the number of chars til '\0'.
    I my case i've alloced space for 80 chars,
    so when I'm strduping, will my new array also hold 80 or just till the strlen of the old char array?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
  char* str1 =(char *) malloc(80*sizeof(char));
  printf("length of str1:%d\n",(int)strlen(str1));
  str1 = "test_of_string\n";
  printf("length of str1:%d\n",(int)strlen(str1));

  char* str2 = strdup(str1);
  printf("length of str1:%d\n",(int)strlen(str2));
  return 0;


Member Avatar
Posting Sage
7,177 posts since Dec 2005
Reputation Points: 5,138 [?]
Q&As Helped to Solve: 970 [?]
Skill Endorsements: 41 [?]
Team Colleague

Because malloc returns memory which is filled with garbage, then you try and "read" that memory (using strlen) to find a \0

Besides which, it's also a memory leak.
Delete lines 6 and 7, and just go with char *str1 = "test_of_string\n"; > so when I'm strduping, will my new array also hold 80 or just till the strlen of the old char array?
Minimally, just the space needed for the characters and a \0.

Though since strdup() is just a malloc + strcpy, the amount actually allocated is usually rounded up for efficiency purposes.
But there is no way to tell that has happened, as all you officially have is strlen()+1 bytes.

Member Avatar
Junior Poster
144 posts since Oct 2008
Reputation Points: 9 [?]
Q&As Helped to Solve: 11 [?]
Skill Endorsements: 0 [?]

Here you are allocating memory

char* str1 =(char *) malloc(80*sizeof(char));

but this memory has not been initialized to zero by malloc

The following may or may not fail because the contents of the
allocated memory are totally random! But, if it does not fail, it is guaranteed to return and incorrect result.

printf("length of str1:%d\n",(int)strlen(str1));

In the next line of code you lose the abily to free the allocated
memory because you point the allocated memory pointer to a
string - hence the memory leak.

str1 = "test_of_string\n";
This article has been dead for over three months: Start a new discussion instead
Start New Discussion
Tags Related to this Article