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;


7 Years
Discussion Span
Last Post by fpmurphy

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.


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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.